Search code examples
c#webview2winuiwinui-3

Get response from post in WebView2 in WinUI 3.0 Preview 3 Desktop App


In the ctor of the code-behind we have the code below copied from microsoft-ui-xaml-specs

MyWebView.WebMessageReceived += (WebView2 sender, WebView2WebMessageReceivedEventArgs args) =>
{
    // Important to validate that the Uri is what we expect from that webview.
    string uriAsString = sender.Source.ToString();

    if (args.Source == uriAsString)
    {
        HandleWebMessageAsString(args.WebMessageAsString);
        HandleWebMessageAsJson(args.WebMessageAsJson);
    }

    else
    {
        // If the source is not validated, don't process the message.
        return;
    }
};

Edit 1: The event handler is registered before the WebView navigates to a page. The POST is not part of our page. POST is from a button instantiated by javascript injected into our page from an external service.

The xaml

<WebView2 
    Name="MyWebView"  Grid.Row="1" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
    />

The WebView2 navigates and posts correctly. We own the page in the WebView and we know the page gets a response. But MyWebView.WebMessageReceived isn't hit.

According to the WinUI 3.0 Feature Roadmap WebView2 should be implemented in WinUI 3 Preview 3.

Should I be able to read the response? If so, where did I go wrong?


Solution

  • If you have registered for the WebMessageReceived event but aren't seeing your event handler run you might check the following:

    1. Ensure you register for the WebMessageReceived event before the webpage you load executes the chrome.webview.postMessage. If you register the event handler after the page posts the message, the event handler won't fire. Similarly, you must watch out for races. For instance, if you navigate to a page that executes postMessage while the page is loading and then register the WebMessageReceived event there's no guarantee which will finish first and you may or may not receive the message.
    2. Ensure the code in your page is actually running chrome.webview.postMessage and successfully. You can use the DevTools in the WebView2 to put a breakpoint on that line of code in your page and validate that it executes and that you don't throw an exception before running that code.