JavaScript event handling in WKWebView

I try to catch every event onClickin WKWebView. The website only works with JavaScript, so I cannot process anything in:

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

How can i do this?

+3
source share
2 answers

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

    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 enter it on 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
    }
+4
source

You can use WebViewJavascriptBridge. Please refer to the link below:

https://github.com/marcuswestin/WebViewJavascriptBridge

0

All Articles