uniapp webview 与vue2页面双向通信

一、准备工作

uniapp:

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

vue: 安装webview用到的依赖

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

  

二、vue向webview传递消息

vue部分:

1
2
3
uniWebview.postMessage({
  data: { 数据}
})

uniapp部分:

1
2
3
4
5
//handlePostMessage已经在上面绑定到webview上
 
handlePostMessage: function(res) {
  console.log(res)
}

三、webview向vue传递消息  

vue部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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部分:

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

 

posted on   嗨哆嚒  阅读(968)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

点击右上角即可分享
微信分享提示