Search code examples
webviewwindows-community-toolkit

How to add a list of allowed URI's for WebView's "ScriptNotify" in a WPF app?


I'm trying to call a C# method using "window.external.notify('my message');" from JavaScript and it doesn't appear to be working. My guess is that I have to add the current window.location a list of allowed domains, but how can I do this in a WPF app? Everything I see online relates to UWP.

    private void WebView_ScriptNotify(object sender, WebViewControlScriptNotifyEventArgs e)
    {
        throw new NotImplementedException();
    }

    private void WebView_DOMContentLoaded(object sender, WebViewControlDOMContentLoadedEventArgs e)
    {
        webView.InvokeScript("eval", new string[] {@"window.external.notify('{}');"});
    }

Solution

  • Make sure you set the IsScriptNotifyAllowed and IsJavaScriptEnabled properties to true, then the event should fire.

    Edit: there is a bug in the WPF WebView in the 3.0.0 package. An issue has been opened on GitHub to resolve it.

    Edit 2: the bug is fixed in version 4.0.0 of the package. I'm working with the community now to port the fix to service 3.0.0. PR 2346

    Edit 3: the bug is also fixed in the 3.0 servicing branch. Will update when a new package is published to NuGet

    Edit 4: the bug is fixed and new packages have been pushed to NuGet