How can I prevent a Windows Runtime WebView from loading any content beyond the initial request and its redirects?

Raymond

Last time, we configured a Windows Runtime WebView control so that it loaded content only from the initial request, and all other requests were blocked. However, we found that this meant that if the original request resulted in a redirect, we blocked the redirect.

How can we allow the redirects?

When the initial request is made, or when a redirect is followed, the WebView control raises the Navigation­Starting event. We can listen to that event to follow the redirects.

Start afresh with the WebView sample and make these changes.

    public Scenario1_NavToUrl()
    {
        this.InitializeComponent();
        WebViewControl.WebResourceRequested += OnResourceRequested;
    }

    Uri allowedUri = null;

    void OnResourceRequested(WebView sender,
             WebViewWebResourceRequestedEventArgs e)
    {
        if (e.Request.RequestUri != allowedUri)
        {
            e.Response = new Windows.Web.Http.HttpResponseMessage(
                             Windows.Web.Http.HttpStatusCode.NotFound);
        }
    }

    void WebViewControl_NavigationStarting(WebView sender,
             WebViewWebResourceRequestedEventArgs e)
    {
        string url = UriToString(args.Uri);
        AddressBox.Text = url;
        allowedUri = args.Uri;
        AppendLog($"Starting navigation to: \"{url}\".");
        pageIsLoading = true;
    }

This time, we update the allowedUri when a navigation starts, which happens either in the original navigation or as the result of a redirect.

Note that Navigation­Starting is also raised when the user triggers a navigation by clicking a link, or if script on the page triggers its own navigation. If you want to block those, you can listen for the Navigation­Complete event and reject any subsequent navigations, or at least stop allowing them.

0 comments

Comments are closed. Login to edit/delete your existing comments