WKWebView与JS交互

APP有时会套一个网页在里面,此时Native与网页JS进行通信也是经常要用的到的。贴上小小的粟子

let configuration = WKWebViewConfiguration()
configuration.preferences = WKPreferences()
configuration.preferences.javaScriptEnabled = true
//通过js与webview内容交互配置
configuration.userContentController = WKUserContentController()
        
//往HTML里面注入脚本
//let script = WKUserScript(source: "alert('success'); ",injectionTime: .AtDocumentStart,// 在载入时就添加JS 此方法只在指定的时间点有效
forMainFrameOnly: true) // 只添加到mainFrame中 //configuration.userContentController.addUserScript(script) //JS调用Native时要注册此方法,注意名字是个Key。这里要注意第一个参数是要实现了WKScriptMessageHandler接口的类名 configuration.userContentController.addScriptMessageHandler(self, name: "ScanQRCode")
//好了,现在网页JS可以通过以下脚本与Native通信了 //window.webkit.messageHandlers.<name>.postMessage({<content>}) for example: window.webkit.messageHandlers.ScanQRCode.postMessage({body:'hello guy'}) wkBrowser = WKWebView(frame: CGRectMake(0, 20, self.view.bounds.width, self.view.bounds.height-20), configuration: configuration)

 实现WKScriptMessageHandler内的方法,JS调用Native端会触发此方法

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        if message.name == "ScanQRCode" { //这个名称与上面配置的要一样,
            
            //It work by this way
            //self.wkBrowser.evaluateJavaScript("document.getElementById('abc').innerHTML='sssssss'", completionHandler: nil)
            //通过message.body获取从JS传递过来的参数,可以传JSON或者其它格式
            let id = message.body as! String
            
            /*let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ScanViewController") as! ScanViewController
            controller.delegate = self
            controller.htmlId = id
            //controller.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.9)
            self.modalPresentationStyle = UIModalPresentationStyle.FullScreen
            self.presentViewController(controller, animated: true, completion: { () -> Void in
                //controller.view.backgroundColor = UIColor.clearColor()
            })*/

        }

 从Native调用网页的方法或者运行脚本可以用到以下代码

self.wkBrowser.evaluateJavaScript("$(#"abc").val('I am come from native')", completionHandler: nil)
原文地址:https://www.cnblogs.com/foxting/p/4951465.html