"要在 WKWebView 中监听并打印 console.log 消息,你需要实现 WKScriptMessageHandler 协议。以下是一个示例实现:\n\n1. 在你的 ViewController 中,添加 WKScriptMessageHandler 协议:\n\nswift\nclass ViewController: UIViewController, WKScriptMessageHandler {\n // ...\n}\n\n\n2. 在你的 ViewController 中,创建一个 WKWebView 实例,并将其配置为使用你实现的 WKScriptMessageHandler:\n\nswift\nlet configuration = WKWebViewConfiguration()\nlet userContentController = WKUserContentController()\nuserContentController.add(self, name: \"consoleLog\")\nconfiguration.userContentController = userContentController\n\nlet webView = WKWebView(frame: view.bounds, configuration: configuration)\nview.addSubview(webView)\n\n\n3. 实现 WKScriptMessageHandler 协议的方法,以处理来自 WebView 中 console.log 的消息:\n\nswift\nfunc userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {\n if message.name == \"consoleLog\", let logString = message.body as? String {\n print(\"Console.log: \" + logString)\n }\n}\n\n\n4. 在你的网页中,使用 JavaScript 代码来发送 console.log 消息给 WKWebView:\n\njavascript\nconsole.log(\"Hello from JavaScript!\")\n\n\n当网页中发出 console.log 消息时,它将被传递到你的实现的 userContentController(:didReceive:) 方法中,并在控制台中打印出来。\n\n请注意,你还需要将 WKWebView 添加为 ViewController 的子视图,并加载你的网页。你可以使用 load(:) 方法来加载网页。\n

WKWebView 监听 Console.log 消息:使用 WKScriptMessageHandler 协议

原文地址: https://www.cveoy.top/t/topic/qzmo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录