web-view内嵌H5与uniapp数据的实时传递

场景:

在 uni-app 中通过 web-view 内嵌 H5 ,要做到在 H5 发起传递信息传给 uni-app 并且 uni-app 能实时接收。


解决方案:

1.在uni-app项目的main.js文件中引入和创建一个事件总线对象:

import Vue from vue
export const EventBus = new Vue()

2.在uni-app中定义一个事件监听函数,在该函数中实现对来自web-view的消息进行处理:

import {
          
   EventBus} from @/main.js

// 监听事件
EventBus.$on(messageFromH5, (data) => {
          
   
  // 处理来自web-view的消息
  console.log(收到来自H5页面的消息:, data)
})

3.在web-view的H5页面中使用postMessage()方法向uni-app页面发送消息,同时将发送的消息格式转换为对象格式:

var messageData = {
          
   
  content: 这是从H5页面中发送的消息
}

var sendData = JSON.stringify(messageData)
window.parent.postMessage(sendData, *)
    在调用postMessage方法时,第二个参数需要指定为’*,表示任意域名都可以接收到消息。 uniapp的web-view组件的onMessage中的回调函数,只有在页面还没有被销毁前才会响应,因此需要在页面销毁前即可获得消息,如果需要在后退和分享时也能获得消息,则需要在生命周期函数onUnload中清理原有的web-view,再重新生成web-view,并在重新生成的web-view中监听消息。 在web-view中使用postMessage方法发送数据时,需要确保发送的数据是一个标准的JSON对象,避免其他数据格式的问题而导致消息无法被正确接收。

4.在web-view组件标签中设置onMessage属性,监听web-view中传过来的消息,并对其进行相应的处理:

<web-view src="https://example.com/h5page" @message="onMessage"></web-view>

export default {
          
   
  methods: {
          
   
    onMessage (event) {
          
   
      // 对从web-view中接收到的消息进行处理
      console.log(收到来自web-view的消息:, event.detail.data)
      // 将消息发送到uni-app中的事件总线
      EventBus.$emit(messageFromH5, event.detail.data)
    }
  }
}

这里的onMessage()方法通过监听web-view的message事件来实现对从web-view中传过来的消息进行处理。同时,将接收到的消息发送到uni-app页面中已经创建的事件总线中,以便不在内嵌的页面也能够接收消息。

经验分享 程序员 微信小程序 职场和发展