Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Why Blazor app showing an error with any page reload

$
0
0

I am working on project with Blazor technology. I need sometimes to use some JS code, and I need to include diffirant js files with each page, and as I know the only way to do it is adding it using JS function and Blazor JS invoke. So what I did is:in _Host.razor

function addScriptFile(fileName){    var script = document.createElement("script");    script.setAttribute("type", "text/javascript");    script.setAttribute("src", file);    document.getElementById(divName).appendChild(script);}

Then in each page (component):

@inject IJSRuntime Js;@functions{    protected override async void OnAfterRender()    {        await Js.InvokeAsync<object>("addScriptFile","~/js/myFile.js");    }}

It is working good, but the problem happening if the page has been reloaded. It throws an errorSystem.InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being prerendered and the page has not yet loaded in the browser or because the circuit is currently disconnected. Components must wrap any JavaScript interop calls in conditional logic to ensure those interop calls are not attempted during prerendering or while the client is disconnected.

What I understand from this error, that I am trying to invoke some javascript code before render completed. So I have used IComponentContext to make sure that the server is connected.In my journey to fixing this issue, I have created a new Blazor project without any JS files, but it throws the same error on reloading page

I tried to make this:

@inject IComponentContext ComponentContext@functions{    protected override void OnAfterRender()    {        if(ComponentContext.IsConnected)        {            //adding scripts        }    }}

How to make JS working with Blazor in suitable way ?And how to fix that error ?


Viewing all articles
Browse latest Browse all 4839

Trending Articles