在 UWP 中设置自定义 WebView 标头 [英] Set custom WebView header in UWP

查看:39
本文介绍了在 UWP 中设置自定义 WebView 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是其他

我在这里分享了我的 UWP 示例强>,您可以轻松集成到您的 Xamarin UWP 应用中.

This could seem to be duplicates of other similar questions but they are old thread and not specific to Windows UWP apps.

I'm unable to set custom header in WebView so the loaded URLs in WebView could work for me.

I have seen many forums giving solution like using HttpClient/WebRequest with header but that doesn't work as in my case, the web address usage Javascript for redirection and before redirection it needs few custom header to load correctly.

Also WebView.NavigateWithHttpRequestMessage is not so suitable as it will postback and I need the headers for each request including javascript redirected URLs in web View.

I'm able to set custom headers in Xamarin.Droid project using Renderers but I couldn't find any solution for UWP Windows.UI.Xaml.Controls.WebView.

解决方案

On Universal Windows 10 Platform, the WebView.NavigateWithHttpRequestMessage method is the right way.

a. I need the headers for each request including javascript redirected URLs in web View.

b. This didn't resolve my issue as after setting the headers the OnWebViewNavigationStarting method is called multiple times and App crashes automatically with System.StackOverflowException error

This is due to the infinite navigation will happen if we do navigation in the NavigationStarting event. We should cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel property to true.

And we need to add/remove handler for NavigationStarting event carefully.

Code sample:

    private void NavigateWithHeader(Uri uri)
    {
        var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri);
        requestMsg.Headers.Add("User-Name", "Franklin Chen");
        wb.NavigateWithHttpRequestMessage(requestMsg);

        wb.NavigationStarting += Wb_NavigationStarting;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        NavigateWithHeader(new Uri("http://openszone.com/RedirectPage.html"));
    }

    private void Wb_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        wb.NavigationStarting -= Wb_NavigationStarting;
        args.Cancel = true;//cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel property to true
        NavigateWithHeader(args.Uri);
    }

The screenshot is the log info in Fiddler, the request record in the second red rectangle included the custom header:

I shared my UWP sample in here, you can easily integrate into your Xamarin UWP app.

这篇关于在 UWP 中设置自定义 WebView 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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