Peter Baer
Peter Baer

Reputation: 1292

Why does WebView.InvokeScriptAsync throw exception 0x80020101 when calling an object added via AddWebAllowedObject?

I have a UWP app in which I have defined the following class in a Windows Runtime Component project within my solution:

[AllowForWeb]
public sealed class WebViewCallback
{
    public string Cookie { get; set; }

    public void reportCookie(string cookie)
    {
        Cookie = cookie;
    }
}

From my main app assembly, I have a WebView (navigated to some URL) where I do the following:

private async void MyWebView_FrameDOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{    
    var callback = new WebViewCallback();
    MyWebView.AddWebAllowedObject("WebViewCallback", callback);

    await MyWebView.InvokeScriptAsync("eval", new[] { "WebViewCallback.reportCookie(document.cookie);" });
}

This throws 0x80020101 (SCRIPT_E_REPORTED), suggesting that the JS engine was not able to find (or not allowed to call) my callback object.

I suspect that somehow I'm not fulfilling the requirements for AddWebAllowedObject as documented in MSDN:

The object passed into AddWebAllowedObject must be imported from a Windows Runtime component that is separate from the app assembly. This is necessary for the AllowForWeb attribute to be property identified by the WebView security subsystem. If you use a class from your app project, AddWebAllowedObject does not work.

Is there maybe something else I need to do with my Windows Runtime Component assembly? I simply added it to my solution like I would any C# assembly.

I'm using VS2017 and Win10 Creators Update.

Upvotes: 0

Views: 631

Answers (1)

Peter Baer
Peter Baer

Reputation: 1292

Figured it out! Apparently AddWebAllowedObject is very sensitive to when it is called. Everything works great if (and apparently only if) AddWebAllowedObject is called in the NavigationStarting event of the WebView. It will silently fail if it is called in some other event handler right before script that uses it is invoked (as I was doing in my repro code).

Upvotes: 1

Related Questions