小工具知识网

当前位置: 首页 > 行业知识 > uniapp纯h5的vue页面和上级webview通信 - window.postMessage方式 - 纯H5版vue页面中的webview无法捕捉html文件的uni.postMessage消息

行业知识

uniapp纯h5的vue页面和上级webview通信 - window.postMessage方式 - 纯H5版vue页面中的webview无法捕捉html文件的uni.postMessage消息

2026-11-12 04:49:43 来源:互联网转载

示例图

问题

问题1:纯H5版vue页面中的uni.postMessage报错未定义 - js文件引用、npm引用都不行;

问题2:H5环境下的webview无法捕捉hybrid/html文件的uni.postMessage消息 - 一点反应都没有;

解决办法

1.纯H5版vue页面中的uni.postMessage报错未定义,那就另辟蹊径,

webview中的vue页面先通过window.location.href跳到项目的hybrid/html某页面中,

再按照官方手册即可引入"uni.webview.1.5.5.js",即可使用

uni.webView.postMessage({

         data: JSON.stringify(sendData)

})

2.H5环境下的webview无法捕捉hybrid/html文件的uni.postMessage消息?

看以下完整代码

window.addEventListener("message", (event) => {

    // 全量打印

    console.log(event)

}, false)

完整代码

hybrid/html

 document.addEventListener('UniAppJSBridgeReady', () => {uni.webView.getEnv((res) => {console.log('webview页面:goback')console.log('当前环境:' + JSON.stringify(res))// pData.ready = true})let sendData = {action: 'back',data: {url: window.location.href}}console.log('webview页面:goback > 跳转命令参数')console.log(JSON.stringify(sendData))uni.webView.postMessage({data: JSON.stringify(sendData)})console.log('webview页面:goback > uni.webView.postMessage完成')console.log('webview页面:goback > 跳转命令发送完成')})

commonWebView.vue

    加载中import { reactive, ref, onMounted } from 'vue'import { onLoad } from '@dcloudio/uni-app'// 风格const webviewStyles = reactive({progress: {color: '#1379ff'}})// 页面数据const pData = reactive({// 地址url: 'https://baidu.rudon.cn/'})/** * APP环境下的接收方法 */const handleWebviewMessage = (data) => {}// webview向外部发送消息const handlePostMessage = (data) => {}// 页面启动onLoad(()=>{// #ifdef H5// uniapp webview h5 通信 window.postMessage 方式// https://blog.csdn.net/qq_42313445/article/details/127068570window.addEventListener("message", (event) => {  // 全量打印  console.log(event)    // 只看关键消息  console.log(event.data)    // hybrid页面通过uni.webView.postMessage传递的data结构  let event_data = event.data.data.arg  console.log(event_data)}, false)// #endif})

... done ...

上一篇:雷神驱动,速度与效率的极致融合揭秘!

下一篇:MySQL如何进行表之间的关联更新