WKWebView Swift - Get Console.log for javascript

I have WKWebView setup, which loadHTMLString(Need to load multiple html files which include JS). I am not able to get the console.log error messages that the JS code produce. I want to get this log within the app. Cannot change settings in safari.


I have tried JSContext(Javascript core) and WKWebView delegate methods, but couldn't find a solution.

I need all the console log messages that is loaded in WKWebView.


Swift version - 4.2 or 5.0


Thank You.

Barath Mohan

Replies

I’ve not done this myself but I believe that you can do this by using a user script (

WKUserScript
) that overrides
console.log
with your own function that routes the the text to your app via a script message (
WKScriptMessage
). I’m not aware of any Apple resources that show this in detail, but you can find a number of third-party resources by searching the ’net for “wkwebview capture console log”.

Also, if you’d like Apple to add an dedicated API for this, I encourage you to file an enhancement request describing your requirements. Please post your bug number, just for the record.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"