在 WebView UWP 中更改默认用户代理 [英] Change default User-Agent in WebView UWP

查看:25
本文介绍了在 WebView UWP 中更改默认用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置自定义 UA 并且我使用

I need set custom UA and I use

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

但是如果我点击页面上的任何链接,这个 UA 就会被删除并设置默认 UA.

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

我发现了同样的问题WebView - 在每个请求上定义 User-Agent 但也许它已修复1607?

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

推荐答案

WebView 不是通用浏览器,它确实有一些限制";目前不支持的.没有可以设置每个请求中使用的默认用户代理的 API.作为一种解决方法,我们可以使用 WebView.NavigationStarting 事件 以及 WebView.NavigateWithHttpRequestMessage 方法在每个请求中设置用户代理.

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.

有关如何执行此操作的更多信息,请参阅此答案.这里的关键点是删除 NavigationStarting 事件的处理程序并取消原始请求中的导航,然后在 NavigateWithHttpRequestMessage 之后添加处理程序以确保 NavigationStarting 事件可以捕获下一个请求,如下所示:

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

这篇关于在 WebView UWP 中更改默认用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆