Handling JavaScript events in WKWebView

If you want to add click listener only for button with id 'buttonX' (<button id="buttonX">Click me</button>) then


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


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
    }