结论:app端支持比较好可以做到实时传递,微信小程序支持比较差,小程序向url传参只能通过url,url向app传参需要特定时机(后退、组件销毁、分享、复制链接)触发才能收到消息。
以下是代码
- app端(需要使用nvue)
<template> <view class="webview-box"> <button style="z-index: 999;" @click="handlePostMessage('app向url传值')">点击向url传值</button><web-view ref="webview" class="webview" src="http://192.168.18.103:8080/index?os=wx" @onPostMessage="PostMessage"></web-view> </view> </template> <script> export default { data() { return { url:'http://192.168.18.103:8080/index?os=wx'} }, onLoad() { this.url += '&t=' + new Date().getTime()}, methods: { // 接收h5页面发来的键值判断需要执行的操作 PostMessage(evt) { console.log("postMessage: ", evt)uni.showModal({title:"提示",content:evt.detail.data[0].msg})}, // 获取到对应webview(关键)通过evalJs(注意大小写,如果不知道evalJ是什么,可自行百度) 执行网页的函数,可对其进行传参,完成与网页的通讯 handlePostMessage(res) { console.log("22")this.$refs.webview.evalJs(`handleMessage('${res}')`); } } } </script> <style> .webview-box { position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; } .webview { flex: 1; height: 300rpx;} </style>
- 微信小程序端(正常vue格式)
<template> <view class="webview-box"> <web-view ref="webview" class="webview" :src="url" @onPostMessage="PostMessage" @message="PostMessage"></web-view> </view> </template> <script> export default { data() { return { url:'http://192.168.18.103:8080/index?os=wx'} }, onLoad() { this.url += '&t=' + new Date().getTime()}, methods: { // 接收h5页面发来的键值判断需要执行的操作 PostMessage(evt) { console.log("postMessage1: ", evt) }, // 获取到对应webview(关键)通过evalJs(注意大小写,如果不知道evalJ是什么,可自行百度) 执行网页的函数,可对其进行传参,完成与网页的通讯 handlePostMessage(res) { console.log("22")} } } </script> <style> .webview-box { position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; } .webview { flex: 1; height: 300rpx;} </style>
3、html端
<!doctype html> <html lang="ch" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no,viewport-fit=cover"><title>默认的title</title><!-- 微信 JS-SDK 如果不需要兼容小程序,则无需引用此 JS 文件。 --> <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script> <!-- uni 的 SDK,必须引用。 --> <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script><body><div id="box"></div><div class="btn" >点击1</div><button id="to_shiming">向上传递数据</button></body><script> // 在引用依赖的文件后,需要在 HTML 中监听 UniAppJSBridgeReady 事件触发后,才能安全调用 uni 的 API。 document.addEventListener('UniAppJSBridgeReady', function() {// 下面就是js知识了,点击某个按钮后发消息。document.getElementById('to_shiming').addEventListener('click', function() {// 这里调用uniapp的api执行消息发送uni.postMessage({data: {msg:'url向app传值'}});});});window.handleMessage = function(msg){console.log("接收到消息",msg);alert("接收到消息"+msg);document.getElementById('box').innerText = msg;}</script> </head></html>