Changing the default user agent in WebView UWP

I need to install custom UA and use

httpRequestMessage.Headers.Add("User-Agent", "blahblah"); theWebView.NavigateWithHttpRequestMessage(httpRequestMessage); 

But if I click on any link on the page, UA will remove and set UA by default.

I found the same WebView question - Define User-Agent for each request , but maybe it was fixed in 1607?

+5
source share
1 answer

WebView is not a universal browser, it has some "limitations" that are not supported now. The API cannot set the default User-Agent, which is used in every request. As a workaround, we can use the WebView.NavigationStarting event along with WebView. NavigateWithHttpRequestMessage to install the User-Agent in each request.

For more on how to do this, see this answer . The key point here is to remove the NavigationStarting event handler and cancel the navigation in the original request, and then add the handler after NavigateWithHttpRequestMessage to make sure that the NavigationStarting event can capture the following requests, for example:

 WebView wb = new WebView(); wb.NavigationStarting += Wb_NavigationStarting; ... private void NavigateWithHeader(Uri uri) { var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri); requestMsg.Headers.Add("User-Agent", "blahblah"); wb.NavigateWithHttpRequestMessage(requestMsg); wb.NavigationStarting += Wb_NavigationStarting; } private void Wb_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { wb.NavigationStarting -= Wb_NavigationStarting; args.Cancel = true; NavigateWithHeader(args.Uri); } 

In addition, you can vote UserVoice to share your reviews.

+6
source

All Articles