在Blazor服务器端应用程序中无法从OnAfterRenderAsync使用JsRuntime.InvokeAsync

时间:2019-10-19 18:55:31

标签: javascript c# blazor-server-side

我有一个Blazor应用,在OnAfterRenderAsync中,我正在调用方法PlayVideo(),该方法需要调用JavaScript方法。在以前的Blazor版本中,我可以检查context.IsConnected属性以确保可以进行JavaScript调用。但是,在最新版本的Blazor中,此属性已被删除。现在,当我尝试从PlayVideo()方法进行JavaScript调用时,收到以下错误消息:

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.

不过,根据我的阅读,从OnAfterRenderAsync方法调用JavaScript应该可以正常工作,因为它应该已连接。自context.IsConnected属性被删除以来,是否有一种方法可以检查我是否可以进行JavaScript调用?

谢谢你

1 个答案:

答案 0 :(得分:0)

您是否在第一次渲染后检查?

我这样做的方式如下:

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

MS documentation中对此行为进行了描述,希望对您有所帮助。