zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    python分析log
    单词长度统计,字符数量统计直方图
    单词计数
    字符替换
    HP Mobile Center 1.01 Related System Requirements
    字符统计
    文件复制
    C语言,不是从hello world开始
    最近
    echarts Map(地图) 不同颜色区块显示
  • 原文地址:https://www.cnblogs.com/foxting/p/4951465.html
Copyright © 2011-2022 走看看