Search code examples
xamarin.formswebviewxamarin.androidandroid-webviewuser-agent

How can I set the User-Agent in webview of Xamarin.Forms


One of the pages used in my Program needs the UA contains the string "weishao", I have tried to use javascript below to change the UA but it is not working.

var customUserAgent = 'Mozilla/5.0 (Linux; Android 10; EBG-AN00 Build/HUAWEIEBG-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36 weishao(3.2.2.74616)';
            Object.defineProperty(navigator, 'userAgent', {
              value: customUserAgent,
              writable: false
            });

The detector of the page is:

function is_weixin() {
    var href = window.location.href;
    if (href.indexOf("errorPage") != -1){
        return true;
    }
    var ua = navigator.userAgent.toLowerCase();
    var isWeixin = ua.indexOf('micromessenger') != -1;
    var weishao = ua.indexOf('weishao') != -1;
    if (isWeixin){
        return true;
    }else if( weishao) {
        return true;
    }else if(dd.env.platform != "notInDingTalk") {
        return true;
    }else{
        alert("Not allowed!");
        var openid = $("#openid").val();
        if (dkywcommon.isEmpty(openid)) {
            openid = "";
        }
        window.location.href = "/errorPage?openid="+openid;
        return true;
    }
}

Solution

  • Customizing user-agent on webview is not supported currently in xamarin, but if you're just looking for the workaround for xamarin.android , you can refer to the code below .

    [assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))]
    namespace App2.Droid
    {
        public class CustomWebViewRenderer : WebViewRenderer
        {
            private readonly Context _context;
    
            public CustomWebViewRenderer(Context context) : base(context)
            {
                _context = context;
            }
    
            protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
            {
                base.OnElementChanged(e);
    
                if (e.NewElement != null)
                {
                    Control.SetWebViewClient(GetWebViewClient());
                    Control.Settings.UserAgentString = "Custom user agent!";
                }
            }
        }
    }
    

    Refer to

    https://github.com/xamarin/Xamarin.Forms/issues/8432 .