February 19th, 2021

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

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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.

Feedback