WKWebView console log handling? RRS feed

  • Question

  • User390111 posted

    Is there a way to simply programmatically view console logs generated inside of a WKWebView on both Android and iOS? I cannot find a reliable solution for this and need it for production logging. I am currently running a web app that I do not own in the WKWebView, so I cannot modify any of the web content.

    https stackoverflow com a 50755886 This is the only viable solution I have found so far, but it requires overwriting the console log functionality in JS. This "theoretically" should work, but is definitely not the most ideal solution given that I do not own the JS source code I am running within the WKWebView.

    Friday, November 1, 2019 7:01 PM

All replies

  • User369979 posted

    WKWebView is a webkit control of iOS and we can only consume it on the iOS platform. https://stackoverflow.com/a/50755886/8354952 This thread has explained how to implement it on WKWebView. If you want a translation for Xamarin here it is:

    [assembly: ExportRenderer(typeof(MyWebView), typeof(CustomWebViewRenderer))]
    namespace App.iOS
        public class CustomWebViewRenderer : ViewRenderer<MyWebView, WKWebView>, IWKScriptMessageHandler
            WKWebView _wkWebView;
            protected override void OnElementChanged(ElementChangedEventArgs<MyWebView> e)
                if (Control == null)
                    var config = new WKWebViewConfiguration();
                    config.UserContentController.AddScriptMessageHandler(this, "logging");
                    _wkWebView = new WKWebView(Frame, config);
                    string js = @"var console = { log: function(msg){window.webkit.messageHandlers.logging.postMessage(msg) } };";
                    _wkWebView.EvaluateJavaScript(new NSString(js), (result, error) =>
                        if (error != null)
                            Console.WriteLine($"installation of console.log() failed: {0}", error);
                if (e.NewElement != null)
                    // Url is a custom bindable property of MyWebView
                    // I used it here to load the webpage
                    Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Url)));
            public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)

    And WebView on Android can print the log information directly.

    Monday, November 4, 2019 8:32 AM