【问题标题】:Handling JavaScript events in WKWebView在 WKWebView 中处理 JavaScript 事件
【发布时间】:2017-07-12 16:16:24
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

    标签: javascript ios swift wkwebview


    【解决方案1】:

    您可以使用 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
        }
    

    【讨论】:

    • 天哪,我浪费了这么多时间来让它工作!感谢分享:)
    • 太棒了!非常感谢!
    • 有人知道这个概念是否也适用于 Android 吗?
    • @RedRoosterMobile,这个概念也适用于 Android。检查 android.webkit.WebView 上的 addJavascriptInterface 方法
    • @iMRahib,self 是呈现 web 视图的控制器
    【解决方案2】:

    如果您只想为 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 协议

    【讨论】:

      【解决方案3】:

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

      https://github.com/marcuswestin/WebViewJavascriptBridge

      【讨论】:

      • 为什么我要添加一个 3rd 方库,向我的 app bundle 中投放广告,而 WKWebView 已经支持所有具有 Objective-C 风格界面的东西?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多