Change default User-Agent in WebView UWP

人走茶凉 提交于 2019-12-05 08:22:06
Jay Zuo

WebView is not a general-purpose browser, it does have some "limitations" that not supported now. There is no API can set the default User-Agent that 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);
}

Also, you are welcome to vote on UserVoice to share your feedback.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!