Dominick
Dominick

Reputation: 476

Unable to use JsRuntime.InvokeAsync from OnAfterRenderAsync in Blazor Server-Side App

I have a Blazor app and in the OnAfterRenderAsync I'm calling a method PlayVideo() which needs to call a JavaScript method. In previous version of Blazor I was able to check the context.IsConnected property to ensure I could make the JavaScript call. However, in the latest version of Blazor, this property has been removed. Now, in when I try to make the JavaScript call from the PlayVideo() method, I get the following error message:

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.

From what I've read though, calling JavaScript from the OnAfterRenderAsync method should work fine as it should be connected. Is there a way to check now that I can make JavaScript call since the context.IsConnected property has been removed?

Thank YOu

Upvotes: 2

Views: 3609

Answers (1)

Chris Boot
Chris Boot

Reputation: 117

Are you checking that this is after first render?

The way I do this is as follows:

protected async override Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
    // call your JS here
    // await JsRuntime.InvokeVoidAsync 
    }
 }

This behavior is described in the MS documentation I hope this helps.

Upvotes: 3

Related Questions