How to add a custom user agent in the header using a webview and Xamarin Forms

I am writing an app using Xamarin Forms and wanted to control the user agent for my webview. It’s a little hacky way to have the website render differently when it see that it’s my app coming in without having to use session cookies or other crap like that.

It was pretty easy once I found the code, but finding the code was the pain. Well, Add this renderer to your IOS project.

Snippet

using Foundation;
using PrazeMeApp.iOS.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
 
[assembly: ExportRenderer(typeof(WebView), typeof(MyWebViewRenderer))]
namespace PrazeMeApp.iOS.Renderers
{
    public class MyWebViewRenderer : WebViewRenderer
        {
            protected override void OnElementChanged(VisualElementChangedEventArgs e)
            {
            NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject("myuseragentgoeshere"), NSObject.FromObject("UserAgent"));
            NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);
            base.OnElementChanged(e);
            }
        }
    }

 

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *