Closed MichaelCHF closed 2 years ago
When you say it's an error, what error message do you get?
This is something I must investigate. I'll let you know when I release a fix for this.
I've investigated it, and the error is that you can't call GetCoreWebView() inside the DOMContentLoaded method.
WebView2.DOM runs in a different thread, but interacting with the base controls must still be done within a UI thread.
The correct way to invoke it is like this:
private async void DOMContentLoaded(WebView2.DOM.Window window)
{
// Here we're in the browsing context
_ = await webView.Dispatcher.InvokeAsync(async () =>
{
// Here we're back in the UI context
_ = await webView.CoreWebView2.ExecuteScriptAsync("test2()");
});
}
1._ = await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(@"function test2(){alert('test2')}");
private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { await webView.EnsureCoreWebView2Async();