By using the WKWebView apps can load and display either remote webpages or local HTML stored in the app bundle. In both cases the web content is often developed by the same team and there is a need to be able to debug it while running in the WKWebView. Unfortunately there is no console like browsers provide for developers. The console output is missing.
Based on this example this blog post provides a guide on how to add polyfills to WKWebView with native code interaction. As a result you will be able to catch the console output of a webpage loaded in a WKWebView and print it to the Xcode debug console.
We will now setup a bridge between the WKWebView and the ViewController for handling the console functions.
Create a new file and name it domConsole.js. Add the following code to the file. It provides polyfills for the log and the error functions.
To inject these polyfills into the webpage we make use of the WKUserContentController. We also need to setup the ViewController as handler for the two polyfills.
A compiler error will now show up because the ViewController does not conform to the WKScriptMessageHandler protocol. This happens because we added the ViewController as a script message handler to the WKUserContentController. We will fix this by adding an extension for the ViewController and provide native handling for the polyfills.
When running the app in the simulator you will notice that it still doesn’t work. There is one piece missing.
At the place where we setup the WKWebViewConfiguration we need to associate the user content controller with the web view.
Start the simulator again and use the buttons on the webpage to produce console messages. Observe the Xcode debug console. Ta-da! The console messages from the webpage show up there.
Being able to get the console output helped me a lot to debug webpages while having them running in a WKWebView.