Handling JavaScript events in WKWebView

前端 未结 3 1341
忘掉有多难
忘掉有多难 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 11:53

    You can use the WebViewJavascriptBridge. Please refer the below link for details :

    https://github.com/marcuswestin/WebViewJavascriptBridge

    0 讨论(0)
  • 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
        }
    
    0 讨论(0)
  • 2020-12-05 12:15

    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

    0 讨论(0)
提交回复
热议问题