Wednesday, May 26, 2021

Using WebView2 inside WinUI 3 in Desktop project (Part 3)

In Part 2 we added Stop, Reload, Go Back, Go Forward and Inspect possibilities to our WebView 2 project. Now let's cover how to deal with context menu, default dialogs and new windows.

By default, we have got the following context menu for WebView 2 control:

If you want to hide this default context menu, the following piece of code will be helpful:


// add in MainWindow constructor for demo purposes
webView.CoreWebView2Initialized += WebView_CoreWebView2Initialized;

private void WebView_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
	webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
}

In similar way, you can hide standard alert and prompt dialogs and customize them on your own:


private void WebView_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
	webView.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = false;
	webView.CoreWebView2.ScriptDialogOpening += CoreWebView2_ScriptDialogOpening;
}

private void CoreWebView2_ScriptDialogOpening(CoreWebView2 sender, CoreWebView2ScriptDialogOpeningEventArgs args)
{
	if (args.Kind == CoreWebView2ScriptDialogKind.Alert)
	{
		// this is an alert, would you like to display it?
	}

	// always press OK (not the best idea)
	args.Accept();
}

Now imagine, your web page requests to create a new window, for example with window.open() and you need to add some custom processing. This is how you can do it:


private void WebView_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
	webView.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
}

private void CoreWebView2_NewWindowRequested(CoreWebView2 sender, CoreWebView2NewWindowRequestedEventArgs args)
{
	args.Handled = true;
	webView.Source = new Uri(args.Uri);
}

We set here Handled property to true, telling our WebView 2 that it is not necessary to create new window any more. And then, just for demo purposes we redirect current web page to received URL.

Next time in Part 4 we will discuss how to work with JavaScript and how to receive messages from web page in C# code.

No comments:

Post a Comment