简体   繁体   English

在UWP app WebBrowser控件中更改用户代理标头

[英]Changing user-agent header in UWP app WebBrowser control

How do I globally change user-agent header in UWP app WebBrowser control? 如何在UWP app WebBrowser控件中全局更改用户代理标头?

I can change user-agent header in initial url loaded in webbrwser control 我可以在webbrwser控件中加载的初始URL中更改用户代理标头

httpRequestMessage.Headers.Append("User-Agent", ...); 
browser.NavigateWithHttpRequestMessage(httpRequestMessage); 

but any internal link redirect from webpage does not seem to use this custom user-agent header. 但是,从网页重定向的任何内部链接似乎都不使用此自定义用户代理标头。

Unlike Android or iOS, Microsoft does not expose a way to globally change the user-agent in a WebView component. 与Android或iOS不同,Microsoft没有公开全局更改WebView组件中的用户代理的方法。

For individual GET or POST requests, you can set the UA like this: 对于单个GET或POST请求,您可以像这样设置UA:

Uri^ targetURL = ref new Uri("http://www.yourUrlString.com");
HttpClient^ newRequest = ref new HttpClient();
auto headers = newRequest->DefaultRequestHeaders;
headers->UserAgent->TryParseAdd("your user-agent string here");
create_task(newRequest->GetAsync(targetUrl)).then([=](HttpResponseMessageData^ data) 
{
   //Your callback here
});

With that technique, it is possible to connect to the WebView's NavigationStarting event and intercept each request, but I would strongly recommend against it. 使用该技术,可以连接到WebView的NavigationStarting事件并拦截每个请求,但我强烈建议不要使用它。

The WebViewNavigationStartingEventArgs only expose the Uri you were going to navigate to, and the ability to cancel the request. WebViewNavigationStartingEventArgs仅公开您要导航到的Uri,以及取消请求的功能。 It does not expose what type of request it was, nor where the intent came from. 它不公开它是什么类型的请求,也不公开意图的来源。 Because of this, it is impossible to recreate the original navigation intention and you will start to see navigational bugs. 因此,无法重新创建原始导航意图,您将开始看到导航错误。

For example, some web pages have JavaScript elements that make POST requests on button clicks, and if you are intercepting those requests and recreating them as GET requests, the requests will fail and the user's action will be lost. 例如,某些网页具有按钮点击发出POST请求的JavaScript元素,如果您拦截这些请求并将其重新创建为GET请求,则请求将失败,用户的操作将丢失。

Until Microsoft changes this behavior in the WebView, I do not think it is possible to meaningfully change the UA. 在Microsoft在WebView中更改此行为之前,我认为不可能有意义地更改UA。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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