On a recent app I worked on, there was a requirement for authentication within a WebView.  For this to work custom request headers had to be sent through a Xamarin.Forms WebView.  This is quite standard for a lot of hybrid web applications.  I found some resources on the topic, however, all were quite outdated and none had reference to Apple’s new AppStore requirement of WKWebView.  So let’s jump straight into the code.

Shared Code

This code will allow us to use the CustomWebView in XAML.  We can set the header value straight into the XAML or bind it to our ViewModel.

iOS Custom Renderer (WKWebView)

For the iOS custom renderer simply inherit the appropriate ViewRenderer and override OnElementChanged.  In here, set the Control to a new instance of WKWebView.  Then create a NSDictionary with your desired header key and the CustomHeaderValue that we obtain from the shared code we created beforehand.  Create a new NSMutableUrlRequest and set the headers to the dictionary.

Android Custom Renderer (Android.Webkit.WebView)

The Android custom renderer is very similar to that of iOS. Start by inheriting the appropriate ViewRenderer and override OnElementChanged.  In here, set the Control to a new instance of Android.Webkit.Webview.  Then create Dictionary<string, string> with your desired header key and the CustomHeaderValue that we obtain from the shared code we created beforehand.   Set the WebViewClient to a new instance of a CustomWebViewClient with the dictionary created.

Using the Custom Control

The Result

This webpage shows all of the HTTP request headers that have been sent by the WebView. It can be seen that the Authorization header now shows “Bearer MyCustomAuthorizationToken” which has been passed in via my viewmodel.

iOS

Android

That wraps up the entire project, very simple to modify and add multiple headers if required.  Let me know if there are any questions below and I will try to answer them all.

As usual, if you want the entire working example, please have a look here on GitHub.