Handling JavaScript events in WKWebView

前端 未结 3 1360
忘掉有多难
忘掉有多难 2020-12-05 11:26

I\'m trying to catch every onClick event in WKWebView. The website is working only with JavaScript so I cannot handle anything in:



        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 12:13

    you can use a WKUserScript and add it to the userContentController of the WKWebView's configuration.

        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:

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

提交回复
热议问题