美文网首页
WKWebView与vue.js的交互

WKWebView与vue.js的交互

作者: 南南小生 | 来源:发表于2018-11-02 10:36 被阅读466次

    原生调用js的方法

    js写法
    methods:{
      //添加一条数据
        addList(){
          this.listJson.push("1")
        }
    },
    mounted() {
      //将addList方法添加到window中
      //这样原生代码就可以调用addList方法了
      window['addList'] = ()=>{
        this.addList()
      }
    }
    
    Swift写法
    //调用js的addList方法
    self.webView?.evaluateJavaScript("addList()", completionHandler: { (any, error) in
        if (error != nil) {
            print(error.debugDescription)
        }
    })
    

    js调用原生的方法

    js写法
    buttonClick(){
      var str = "恭喜你调用成功"
      //JSObject对象一定要对应上
      window.webkit.messageHandlers.JSObject.postMessage(str);
    }
    
    Swift写法

    1.创建和设置JSObject对象

    let config = WKWebViewConfiguration()
    // 设置偏好设置
    config.preferences = WKPreferences()
    config.preferences.minimumFontSize = 10
    config.preferences.javaScriptEnabled = true
    config.preferences.javaScriptCanOpenWindowsAutomatically = false
    config.processPool = WKProcessPool()
    config.userContentController = WKUserContentController()
    //注意在这里注入JS对象名称 "JSObject"
    config.userContentController.add(self, name: "JSObject")
    self.webView = WKWebView.init(frame: CGRect.init(x: 0, y: UIApplication.shared.statusBarFrame.height+44, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-UIApplication.shared.statusBarFrame.height-44), configuration: config)
    

    2.在代理方法中接收js传过来的信息

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //接收js传过来的内容
        //name:js对象的名字(这里为JSObject)
        //message:js传过来的信息
        let alert = UIAlertController.init(title: message.name, message: message.body as? String, preferredStyle: .alert)
        let sure = UIAlertAction.init(title: "确定", style: .default) { (_) in}
        let canel = UIAlertAction.init(title: "取消", style: .cancel) { (_) in}
        alert.addAction(canel)
        alert.addAction(sure)
        self.present(alert, animated: true, completion: nil)
    }
    

    3.销毁

    override func viewWillDisappear(_ animated: Bool) {
        //这个方法防止内存泄漏,写在合适的位置即可
        self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "JSObject")
    }
    

    demo地址

    https://github.com/DalyLong/WkWebViewAndJS

    相关文章

      网友评论

          本文标题:WKWebView与vue.js的交互

          本文链接:https://www.haomeiwen.com/subject/eupatqtx.html