Maui.net ExecuteScriptAsync(): Failed because a valid CoreWebView2 is not present

138 Views Asked by At

If I want to execute this method:

    private async void GetSessionIdFromWebView()
    {
        sessionId = await webViewer.EvaluateJavaScriptAsync("MauiAppInterface.GetSessionId();");
    }

I got this Exception:

System.InvalidOperationException: "A method was called at an unexpected time.

ExecuteScriptAsync(): Failed because a valid CoreWebView2 is not present. Make sure one was created, for example by calling EnsureCoreWebView2Async() API."

I use the normal WebView and not the Webview2.

        <WebView x:Name="webViewer" />

In addition, the webview is not null when the above method is executed.

At androit and ios it works without problems only in windows i got this Exception.

Does anyone have any idea what the issue is?

WebView source is not null.

enter image description here

1

There are 1 best solutions below

1
Jianwei Sun - MSFT On

System.InvalidOperationException: "A method was called at an unexpected time.

ExecuteScriptAsync(): Failed because a valid CoreWebView2 is not present. Make sure one was created, for example by calling EnsureCoreWebView2Async() API."

About this error, I reproduced it. You can avoid this error as long as you declare Source (just don't make it null), like this:

<WebView x:Name="webViewer" Source=""/>
or
<WebView x:Name="webViewer" Source="https://stackoverflow.com/questions/77700709"/>

BTW, WebView2 is Windows platform, and for Android it's Android.Webkit.WebView, ios is WKWebView. They are all specific things in a specific platform.