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.
