mercredi 4 octobre 2017

Editing the HTTP header done by your WebView using NavigationStarting in a UWP application [HTML,C#]

I recently encounter a very weird issue with how my WebView was doing some of  my HTTP calls on redirects.  Sometimes when calling a URL that will do a redirect the HTTP headers would get lost or replaced by some default values.

To fix this the only solution that I found was to override the HTTP query done every time the WebView started navigating to another page.   In this I was lucky as we have a NavigationStarting event that is fired when this happens, thus I have NavigationStarting += Wb_NavigationStarting; when I am creating my WebView.

Now that ce have caught this event we need to edit  it in Wb_NavigationStarting method, I will unbind the event (so that it dosent fire multiple times), tell the WebView that I am handling the event with args.Cancel = true; and now edit the HTTP query with a method that I will call NavigateWithHeader .

In the method NavigateWithHeader I will just add again my header and my authorization token so that the HTTP query has all of the values it is supposed to have, you will have something like this:

var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri);
requestMsg.Headers.Add("User-Agent", "some user agent");
requestMsg.Headers.Add("Authorization", "token abc");                      
MyWebView.NavigateWithHttpRequestMessage(requestMsg);
MyWebView.NavigationStarting += Wb_NavigationStarting;


 Here is the full code:


 private WebView NewWebView()
        {
            var webView = new WebView(WebViewExecutionMode.SameThread);
            webView.NavigationStarting += Wb_NavigationStarting;         
            return webView;
        }     

private void NavigateWithHeader(Uri uri)
        {
            var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri);
            requestMsg.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063");
            MyWebView.NavigateWithHttpRequestMessage(requestMsg);
            MyWebView.NavigationStarting += Wb_NavigationStarting;
        }

private void Wb_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            MyWebView.NavigationStarting -= Wb_NavigationStarting;
            args.Cancel = true;
            NavigateWithHeader(args.Uri);
        }

Happy Coding!