.NET Maui WebView: A method was called at an unexpected time.


In attempting to execute JavaScript on a WebView in a .NET MAUI app I was receiving the exception A method was called at an unexpected time.. The exception would occur seemingly at random (sometimes it would happen, sometimes it wouldn't provided the exact same data which indicated I might have a race condition that's occurring). My data was being loaded via a string and not via any HTTP calls.

In the end, something like the below snippet is what ended up getting me up and running. When I was loading the HTML via a string I had made a call to the evaluate JavaScript on the page that tried to run before the WebView had the page fully loaded.

// Assuming webView is your WebView instance
webView.Navigated += WebView_Navigated;

private async void WebView_Navigated(object sender, WebNavigatedEventArgs e)
    if (e.Result == WebNavigationResult.Success)
        var javascriptToExecute = "/* Your JavaScript code that appends HTML into a div tag */";
        await webView.EvaluateJavaScriptAsync(javascriptToExecute);

As an aside, I've also have had inconsistent luck with using EvaluateJavaScriptAsync as well where sometimes it works, and sometimes it doesn't (and I have not been able to nail down that case). The workaround however is to call the sync version Eval which always work. I'm sure there's a gotcha I'm not aware of and if I find it I'll update this post.