uniapp webview 与vue2页面双向通信

发布时间 2023-07-26 10:14:49作者: 嗨哆嚒

一、准备工作

uniapp:

//建立工程,创建显示的页面
<web-view src="http://192.168.0.58:8080" @message="handlePostMessage"></web-view>

vue: 安装webview用到的依赖

yarn add @dcloudio/uni-webview-js 
import uniWebview from '@dcloudio/uni-webview-js'

  

二、vue向webview传递消息

vue部分:

 uniWebview.postMessage({
   data: { 数据}
 })

uniapp部分:

//handlePostMessage已经在上面绑定到webview上

handlePostMessage: function(res) {
  console.log(res)
}

三、webview向vue传递消息  

vue部分:

  mounted () {
    //监听页面准备完毕
    document.addEventListener('UniAppJSBridgeReady', 
    this.UniAppJSBridgeReady)
  },
  beforeDestroy () {
    //销毁时移除监听和函数
    window.msgFromUniapp = null
    document.removeEventListener('UniAppJSBridgeReady', 
    this.UniAppJSBridgeReady)
  },
  methods: {
    UniAppJSBridgeReady () {
     //定义一个函数,挂载在window上,在uniapp中调用实现消息传递
      window.msgFromUniapp = (arg) => {
        console.log(arg)
      }
    }
  }

uniapp部分:

//在需要的地方调用
data = {msg: 'msg from uniapp'};
const currentWebview = this.$scope.$getAppWebview().children()[0];
currentWebview .evalJS(`${funName}(${JSON.stringify(data)})`);