简体   繁体   English

在 WKWebView 中处理 JavaScript 事件

[英]Handling JavaScript events in WKWebView

I'm trying to catch every onClick event in WKWebView .我正在尝试捕获WKWebView中的每个onClick事件。 The website is working only with JavaScript so I cannot handle anything in:该网站仅使用 JavaScript,因此我无法处理以下内容:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

How can I do this?我怎样才能做到这一点?

you can use a WKUserScript and add it to the userContentController of the WKWebView's configuration.您可以使用 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)

this will make the script and inject it into the page when the document is finished loading.这将生成脚本并在文档加载完成后将其注入页面。 Now, you need to implement the WKScriptMessageHandler protocol to receive the message:现在,您需要实现 WKScriptMessageHandler 协议来接收消息:

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("message: \(message.body)")
        // and whatever other actions you want to take
    }

If you want to add click listener only for button with id 'buttonX' ( <button id="buttonX">Click me</button> ) then如果您只想为 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")
        }
    }

Also your view controller should conform to WKScriptMessageHandler protocol此外,您的视图控制器应符合WKScriptMessageHandler协议

You can use the WebViewJavascriptBridge.您可以使用 WebViewJavascriptBridge。 Please refer the below link for details:详情请参考以下链接:

https://github.com/marcuswestin/WebViewJavascriptBridge https://github.com/marcuswestin/WebViewJavascriptBridge

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM