From 01b66fa9fbecce8d6f0049e169d01217e191fc66 Mon Sep 17 00:00:00 2001 From: Sander Hautvast Date: Wed, 21 Feb 2024 14:05:19 +0100 Subject: [PATCH] Create WKWebView_logging.md --- IOS/WKWebView_logging.md | 48 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 IOS/WKWebView_logging.md diff --git a/IOS/WKWebView_logging.md b/IOS/WKWebView_logging.md new file mode 100644 index 0000000..2f48b26 --- /dev/null +++ b/IOS/WKWebView_logging.md @@ -0,0 +1,48 @@ +```swift +import SwiftUI +import WebKit +import JavaScriptCore + +struct ContentView: View { + var body: some View { + WebView() + } +} + +#Preview { + ContentView() +} + +struct WebView: UIViewRepresentable { + + let webView: WKWebView + + init() { + webView = WKWebView(frame: .zero) + + } + + func makeUIView(context: Context) -> WKWebView { + let source = "function captureLog(msg) { window.webkit.messageHandlers.logHandler.postMessage(msg); } window.console.log = captureLog;" + let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false) + webView.configuration.userContentController.addUserScript(script) + // register the bridge script that listens for the output + webView.configuration.userContentController.add(Controller(), name: "logHandler") + + return webView + } + func updateUIView(_ uiView: WKWebView, context: Context) { + webView.load(URLRequest(url: URL(string: "http://localhost:8000/demo")!)) + } +} + + +class Controller: NSObject, WKScriptMessageHandler{ + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + if message.name == "logHandler" { + print("LOG: \(message.body)") + } + } +} + +```