简体   繁体   中英

Change default User-Agent in WebView UWP

I need set custom UA and I use

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

But if I click any link on page this UA erased and set default UA.

I found same question WebView - Define User-Agent on every request but maybe it fixed in 1607?

WebView is not a general-purpose browser, it does have some "limitations" that are not currently supported. There is no API that can set the default User-Agent that's used in every request. As a workaround we can use WebView.NavigationStarting event along with WebView.NavigateWithHttpRequestMessage method to set User-Agent in every request.

For more information about how to do this, please refer to this answer . The key point here is removing handler for NavigationStarting event and cancelling navigation in the original request and then adding the handler after NavigateWithHttpRequestMessage to make sure NavigationStarting event can capture next requests like following:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM