uniapp 开发app 与 H5 之间通信

芸殇
2024-04-17 / 0 评论 / 266 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年04月17日,已超过927天没有更新,若内容或图片失效,请留言反馈。

H5 向 app 传递消息

引入 uni.webview.1.5.1.js

  项目是使用的 Vue3 + TS 写的 H5 页面,所以需要再 index.html 文件中引入 uni.webview.1.5.1.js 。

<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js"></script>

使用 uni.postMessage 向app传递消息

  在项目中我们使用 uni.postMessage 来向 app 传递消息。

const openTripartiteMap = () = > {
  uni.postMessage({data: { 
    name: '****'
  }})
}

  如果项目是用 TS 写的,在这里可能会遇见 uni 过不去 TS 检测的问题,从而导致无法打包,所以这里我们需要用 @ts-ignore 来让 TS 忽略单行检测。@ts-ignore 需要写在需要忽略的那行代码上面。

const openTripartiteMap = () = > {
  // @ts-ignore
  uni.postMessage({data: { 
    name: '****'
  }})
}

在 app 中接收消息

  在 app 中使用 web-view 来承接 H5

<web-view :src="url" @message="getMessage" @onPostMessage="getPostMessage"></web-view>
getMessage(e) {
  console.log("@message 接收成功")
  if (e.detail) {
    console.log('根据h5传值,调用不同的方法,实现h5与app的交互', e.detail)
  }
},
// 方法兼容
getPostMessage(e) {
  console.log("@onPostMessage 接收成功")
  if (e.detail) {
    console.log('根据h5传值,调用不同的方法,实现h5与app的交互', e.detail)
  }
}
1

评论 (0)

取消