0
votes

I have web view application and try To Read All Of The javascript Console.log and clicked event of the web view in my application

I write this code , when button is clicked go to userContentController delegate but when have message nothing happen

let config = WKWebViewConfiguration()
        let source = """
        document.addEventListener('click', function(){ window.webkit.messageHandlers.iosListener.postMessage('click clack!'); })
        document.addEventListener('message', function(e){
            window.webkit.messageHandlers.iosListener.postMessage(e.data); })
        })
        """
        let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
        config.userContentController.addUserScript(script)
        config.userContentController.add(self, name: "iosListener")


How can I read console.log of wkwebview messages swift? in UIwebview I can use

 let context = self.webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext

        let logFunction : @convention(block) (String) -> Void =
        {
            (msg: String) in

            NSLog("Console: %@", msg)
        }
       context.objectForKeyedSubscript("console").setObject(unsafeBitCast(logFunction, to: AnyObject.self), forKeyedSubscript: "log" as NSString)

but in wkwebview it dosent work

1

1 Answers

2
votes

If I understand well you want to redirect the console.log of the document to your app log.

I would suggest this solution:

This is the script to add to your webview using WKUserScript as you did.

    var console = (function (oldConsole) {
      return {
        ...oldConsole,
        log: function(msg) {
          window.webkit.messageHandlers.iosListener.postMessage(msg);
          oldConsole[level](msg);
        }
      }
    })(window.console);

Then you will receive msg of all your console.log(msg) in the message handler you have specified.

If you want to track more than just the console.log you can elaborate the script with something like this:

extension WKWebView {

     func redirectConsole(messageHandlerName: String) {
        let script = """
        var console = (function (oldConsole) {
          function redirect(level) {
            return function(msg) {
              window.webkit.messageHandlers.\(messageHandlerName).postMessage({ method: "console", level: level, content: JSON.stringify(msg) })
              oldConsole[level](msg);
            };
          }
          return {
            ...oldConsole,
            log: redirect("log"),
            info: redirect("info"),
            warn: redirect("warn"),
            error: redirect("error"),
          }
        })(window.console);
        """
        evaluateJavaScript(script) { _, error in
            if let error = error {
                log(error.localizedDescription)
            }
        }
    }
}

...and I process the log from the webview in my messageHandler.