【发布时间】:2019-02-16 08:21:34
【问题描述】:
我有 Web 视图应用程序并尝试在我的应用程序中读取所有 javascript Console.log 和单击 Web 视图事件
我写了这段代码,当按钮被点击时转到 userContentController 委托,但是当有消息时什么都没有发生
let config = WKWebViewConfiguration()
let source = """
document.addEventListener('click', function(){ window.webkit.messageHandlers.iosListener.postMessage('click clack!'); })
document.addEventListener('message', function(e){
window.webkit.messageHandlers.iosListener.postMessage(e.data); })
})
"""
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
config.userContentController.addUserScript(script)
config.userContentController.add(self, name: "iosListener")
如何快速读取 wkwebview 消息的 console.log? 在 UIwebview 我可以使用
let context = self.webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
let logFunction : @convention(block) (String) -> Void =
{
(msg: String) in
NSLog("Console: %@", msg)
}
context.objectForKeyedSubscript("console").setObject(unsafeBitCast(logFunction, to: AnyObject.self), forKeyedSubscript: "log" as NSString)
但在 wkwebview 中它不起作用
【问题讨论】: