How to inject JavaScript callback to detect onclick event, using iOS WKWebView?

前端 未结 4 1555
灰色年华
灰色年华 2021-02-01 06:14

I\'m using a WKWebView to show a website which has some HTML that includes three buttons. I want to run some Swift code in the native app when a specific button is

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 06:31

    Here goes the implementation in detail:

     var webView: WKWebView?
     var webConfig:WKWebViewConfiguration {
     get {
    
        let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
        let userController:WKUserContentController = WKUserContentController()
        userController.add(self, name: "submit")
        let js:String = buttonClickEventTriggered()
        let userScript:WKUserScript =  WKUserScript(source: js, injectionTime:WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        userController.addUserScript(userScript)
        webCfg.userContentController = userController;
        return webCfg;
    }
    }
    override func viewDidLoad() {
    super.viewDidLoad()
    self.webView = WKWebView(frame: self.view.frame, configuration: webConfig)
    self.webView!.navigationDelegate = self
    self.view = webView!
    let url = URL(string:"your URL here")
    let req = NSURLRequest(url:url! as URL)
    self.webView!.load(req as URLRequest)
    }
    
     func buttonClickEventTriggered() ->String{
    
    let script:String = "document.getElementById('your button id here').addEventListener('click', function () {window.webkit.messageHandlers.submit.postMessage('submited');});"//Make sure you have mapped the name correctly under userController.add
    return script;
    }
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("Sucessss")
    if(message.name == "submit") {
        print("It does ! \(message.body)")
        // Your code goes here
    }
    }
    

提交回复
热议问题