在 WKWebView 中处理 JavaScript 个事件

Handling JavaScript events in WKWebView

我正在尝试捕捉 WKWebView 中的每个 onClick 事件。 该网站仅适用于 JavaScript,因此我无法处理以下内容:

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
    }

您可以使用 WebViewJavascriptBridge。详情请参考以下link:

https://github.com/marcuswestin/WebViewJavascriptBridge

如果您只想为 ID 为 'buttonX' (<button id="buttonX">Click me</button>) 的按钮添加点击监听器,则


let scriptSource = """
var button = document.getElementById('buttonX');
document.body.style.backgroundColor = `red`;
if(button != null) {
    button.addEventListener("click", function(){
        window.webkit.messageHandlers.iosClickListener.postMessage('open_invitation');
        document.body.style.backgroundColor = `green`;
    });
}

"""

        let config = WKWebViewConfiguration()
        let script = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: false)

        config.userContentController.addUserScript(script)
        config.userContentController.add(self, name: "iosClickListener")


        let webView = WKWebView(frame: view.frame, configuration: config)

        view.addSubview(webView)
        webView.loadHTMLString(html, baseURL: nil) //load your html body here

    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if let body = message.body as? String, body == "open_invitation" {
            print("✅ we did it")
        }
    }

此外,您的视图控制器应符合 WKScriptMessageHandler 协议