How to add custom HTTP headers in WebView (all requests + css + js)?

dimikkdimikk RUMember ✭✭
edited April 2017 in Xamarin.Forms

Hello!
I already did this with custom WebViewRender and MyWebViewClient, but I think that it can be done better for iOS and Android.
I will appreciate any help. If this can be made easier with only the help of the PCL.
Thanks!

    public class WebViewRender : WebViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                var webView = Control as Android.Webkit.WebView;
                Dictionary<string, string> headers = new Dictionary<string, string>
                {
                    ["Name"] = "value"
                };
                webView.SetWebViewClient(new MyWebViewClient());
                webView.LoadUrl(Control.Url, headers);
            }
        }
    }
    public class MyWebViewClient : WebViewClient
    {
        public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, string url)
        {
            Dictionary<string, string> headers = new Dictionary<string, string>
            {
                ["Name"] = "value"
            };
            view.LoadUrl(url, headers);
            return true;
        }
    }

Posts

  • dimikkdimikk RUMember ✭✭

    No ideas? I will appreciate any help.

  • john82john82 ITMember ✭✭✭

    Hi,

    I've managed using a custom WebViewClient

        class XtrWebClient : Android.Webkit.WebViewClient
        {
            public override Android.Webkit.WebResourceResponse ShouldInterceptRequest(
                Android.Webkit.WebView view, Android.Webkit.IWebResourceRequest request)
            {
                // Is recursive request? (check for our custom headers)
                if (request.RequestHeaders.ContainsKey("Your Custom Header".ToLower()))
                    return null;
    
                // Add Additional headers
    
                var headers = new Dictionary<string, string>();
    
                foreach (var header in request.RequestHeaders)
                    headers.Add(header.Key, header.Value);
    
                headers.Add("Your Custom Header", "Your Custom Value");
    
                view.LoadUrl(request.Url.ToString(), headers);
    
                return new Android.Webkit.WebResourceResponse("", "", null);
            }
        }
    
  • No any suggestions?

Sign In or Register to comment.