我正在尝试捕捉的所有onClick事件WKWebView。该网站仅使用JavaScript,因此我无法处理以下任何内容:
onClick
WKWebView
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
我怎样才能做到这一点?
您可以使用WKUserScript并将其添加到WKWebView配置的userContentController中。
let config = WKWebViewConfiguration() let source = "document.addEventListener('click', function(){ window.webkit.messageHandlers.iosListener.postMessage('click clack!'); })" let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false) config.userContentController.addUserScript(script) config.userContentController.add(self, name: "iosListener") webView = WKWebView(frame: UIScreen.main.bounds, configuration: config)
这将制作脚本并将文档加载完成后注入到页面中。现在,您需要实现WKScriptMessageHandler协议以接收消息:
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("message: \(message.body)") // and whatever other actions you want to take }