0
votes

I am trying to send a custom string along with the existing user agent in WKWebView, (Xamarin iOS)

    WKWebView WKWebView_New = new WKWebView(View.Frame, new WKWebViewConfiguration());
    var userAgent = WKWebView_New.EvaluateJavaScriptAsync("navigator.userAgent");
    WKWebView_New.CustomUserAgent =  userAgent + " + " + "MyApp";

    Console.WriteLine("User Agent = " + userAgent);
    Console.WriteLine("User Agent + Custom = " + WKWebView_New.CustomUserAgent);

I am seeing this as the user agent:

User Agent = System.Threading.Tasks.Task1[Foundation.NSObject]

User Agent + Custom = System.Threading.Tasks.Task1[Foundation.NSObject] + MyApp

But Expected to see as below:

User Agent = Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15G77

User Agent + Custom = Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15G77 + MyApp

Any help regarding the same will be helpful.

Thank you,

1

1 Answers

0
votes

Use the code below:

 public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            WKWebView WKWebView_New = new WKWebView(View.Frame, new WKWebViewConfiguration());

            WKJavascriptEvaluationResult handler = (NSObject result, NSError err) => {
                if (err != null)
                {
                    System.Console.WriteLine(err);
                }
                if (result != null)
                {
                    System.Console.WriteLine(result);
                    var userAgent = result;
                    WKWebView_New.CustomUserAgent = userAgent + " + " + "MyApp";

                    Console.WriteLine("User Agent + Custom = " + WKWebView_New.CustomUserAgent);
                }
            };

            WKWebView_New.EvaluateJavaScript("navigator.userAgent", handler);

        }

And then you can get the information you expected:

User Agent + Custom = Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16A366 + MyApp