Handling JavaScript events in WKWebView

前端 未结 3 1364
忘掉有多难
忘掉有多难 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:15

    If you want to add click listener only for button with id 'buttonX' () 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

提交回复
热议问题