Show a WKWebView's console.log and JavaScript errors in the Xcode console

WKWebView doesn't forward console.log to Xcode. A 30-line WKScriptMessageHandler bridge sends every log, warning, error and unhandled rejection to the Xcode console and to Console.app.

Cihat SALİK 4 min read

You add a console.log to the page, run the app from Xcode, and the debug area stays empty. Nothing is broken: a WKWebView simply doesn’t route JavaScript console output to your app’s standard output. The page’s console lives in Safari’s Web Inspector, and you only see it once you’ve made the view inspectable and attached from a Mac — the setup for that is here.

Often that is all you need. But there are good reasons to want the logs in Xcode as well:

  • you want web logs interleaved with your native logs, in order, to see which side fired first;
  • the bug happens on launch, before you can open the inspector;
  • a tester’s device is not on your desk, and Console.app or a sysdiagnose is what you’ll get back;
  • you are on a machine where the inspector won’t attach and you need something now.

The fix is a small bridge: a user script that wraps console, and a native message handler that receives what it sends.

The JavaScript side

This script is injected at document start, before any page script runs, so even the earliest logs are captured. It forwards each call and still lets the original console method run, so Web Inspector keeps working.

(function () {
  function format(value) {
    if (typeof value === 'string') return value;
    if (value instanceof Error) return value.stack || String(value);
    try { return JSON.stringify(value); } catch (e) { return String(value); }
  }
  function send(level, args) {
    var text = Array.prototype.map.call(args, format).join(' ');
    window.webkit.messageHandlers.console.postMessage({ level: level, message: text });
  }
  ['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) {
    var original = console[level];
    console[level] = function () {
      send(level, arguments);
      original.apply(console, arguments);
    };
  });
  window.addEventListener('error', function (event) {
    send('error', [event.message + ' (' + event.filename + ':' + event.lineno + ')']);
  });
  window.addEventListener('unhandledrejection', function (event) {
    send('error', ['Unhandled rejection: ' + format(event.reason)]);
  });
})();

Two details matter. JSON.stringify turns an Error into {}, so errors are formatted from their stack instead. And the error and unhandledrejection listeners catch the failures nobody logged on purpose, which are usually the interesting ones.

The Swift side

window.webkit.messageHandlers.console exists because the app registers a handler with that name on the configuration’s WKUserContentController:

import OSLog
import WebKit

final class WebConsoleBridge: NSObject, WKScriptMessageHandler {
    private let logger = Logger(subsystem: "com.example.app", category: "WebConsole")

    func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
        guard let body = message.body as? [String: Any],
              let text = body["message"] as? String else { return }
        switch body["level"] as? String {
        case "error": logger.error("\(text, privacy: .public)")
        case "warn": logger.warning("\(text, privacy: .public)")
        case "debug": logger.debug("\(text, privacy: .public)")
        default: logger.info("\(text, privacy: .public)")
        }
    }
}

func makeWebView(consoleScript: String) -> WKWebView {
    let configuration = WKWebViewConfiguration()
    #if DEBUG
    configuration.userContentController.addUserScript(
        WKUserScript(source: consoleScript, injectionTime: .atDocumentStart, forMainFrameOnly: false)
    )
    configuration.userContentController.add(WebConsoleBridge(), name: "console")
    #endif
    return WKWebView(frame: .zero, configuration: configuration)
}

Using Logger instead of print is deliberate. The messages appear in Xcode’s console with their level, and they also land in the unified log, so you can filter by the WebConsole category in Console.app on a connected device or read them from a tester’s sysdiagnose. The privacy: .public marker is what keeps the text readable outside the debugger; drop it if the page might log personal data.

Three things that bite

The handler is retained strongly. WKUserContentController keeps a strong reference to every handler you add. A dedicated bridge object like the one above is fine. If you make the view controller itself the handler, you have a retain cycle, and you need to call removeScriptMessageHandler(forName:) when the view goes away.

Message bodies are converted. What the page posts arrives as Foundation types — dictionaries, arrays, strings, numbers, NSNull. Functions and DOM nodes don’t cross the bridge, which is another reason to turn everything into a string on the JavaScript side first.

Cross-origin errors are opaque. If a failing script was loaded from another origin without CORS headers, the error event only says “Script error.” with no file or line. That’s WebKit protecting the other origin, not a bug in the bridge.

When the bridge isn’t enough

The bridge shows you what the page says. It won’t show you the DOM, the network waterfall, storage, or let you pause on a breakpoint. For that, make the view inspectable and use Safari’s Web Inspector; if you don’t have a Mac to hand, the comparison of options without a Mac covers what’s left. And if the web view you are trying to debug isn’t in your app at all, read what you can and can’t inspect in someone else’s app.

Frequently asked questions

Why doesn't console.log from a WKWebView show up in Xcode?

Because the page runs in a separate WebKit web content process, and its console belongs to Safari's Web Inspector, not to your app's standard output. Xcode only shows what your app process prints. To get JavaScript logs there, the page has to send them across to native code, which is what a script message handler does.

Should I use this instead of Safari Web Inspector?

Use both. Web Inspector gives you breakpoints, the DOM, the network panel and live editing, and it is the right tool when you are sitting at a Mac with the device attached. The bridge is for the times you can't attach: logs interleaved with your native logs, logs from a tester's device in Console.app, and errors that happen on launch before you could open the inspector.

Does the bridge catch errors from iframes?

Only if the user script is injected into all frames, which is what forMainFrameOnly false does. Errors from cross-origin scripts may still arrive as a bare "Script error." without file or line, because the browser hides details of scripts loaded from another origin unless they are served with CORS.

Is it safe to ship?

Any page loaded in that web view can post to the handler, so keep it to logging and never act on the message content. The example wraps the injection in #if DEBUG; an internal setting works too if testers need logs from release builds.

More on the same subject.

Cihat SALİK

iOS & macOS developer, Istanbul

I write and publish every app on this site on my own, and every guide here came out of building them. Questions reach me directly.