Saturday, June 26, 2021

Injecting Javascript and printing for WebView2 inside WinUI 3 in Desktop project (Part 4)

In Part 3 we discussed new windows, context menus and default dialogs customization. Now let's talk about injecting Javascript into a web page and try to print WebView2 content with the help of Javascript.

Let's add one more button to our sample called "Print" and an event handler for it:


private async void printButton_Click(object sender, RoutedEventArgs e)
{
    string js = "window.print();";
    await webView.CoreWebView2.ExecuteScriptAsync(js);
}

Here we are executing Javascript code passed with the help of string parameter. Note that there is only async version of ExecuteScriptAsync() function. We can pass any Javascript code we want, in this example we say to print the current web page.

From version 0.8 Project Reunion was renamed to Windows App SDK https://github.com/microsoft/WindowsAppSDK

In the next part we will discuss receiving web messages from a page and also making screenshots of a web page.