头图

最近开发遇到一个需求,需要在app与H5页面之间实现通讯

开发环境:app基于uniapp开发,H5端基于uniapp编译

话不多说,直接上代码

// app端,新建一个包含webview标签的页面
<template>
  <web-view :src="link"></web-view>
</template>

<script>
export default {
  data() {
    return {
      link: "H5的网络地址",
    };
  },
  mounted() {
    window.addEventListener("message", this.handleMessage);
  },
  beforeDestroy() {
    window.removeEventListener("message", this.handleMessage);
  },
  methods: {
    handleMessage(data) {
      console.log(data);
    },
  },
};
</script>

<style lang="scss"></style>

H5页面代码

<template>
  <view>
    <view @click="sendMessage">send message</view>
  </view>
</template>

<script>
export default {
  name: "testIndex",
  methods: {
    sendMessage() {
      uni.webView.postMessage({
        data: {
          str: "hello world",
        },
      });
    },
  },
};
</script>

<style>
.text {
  margin-top: 20rpx;
}
</style>

H5端index.html代码(需要导入webview.js)

建议将该静态文件下载到本地后导入

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
  <script>
    var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports(
      'top: constant(a)'))
    document.write(
      '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
      (coverSupport ? ', viewport-fit=cover' : '') + '" />')
  </script>
  <link rel="stylesheet" href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css" />
</head>

<body>
  <noscript>
    <strong>Please enable JavaScript to continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
</body>
<script type="text/javascript"
  src="https://www.testpath.com/webview-js.js"></script>

</html>

首页引用示例

H5端还需要进行如下配置
设置示例

运行两个项目后,点击H5端的发送消息按钮后,控制台查看获取到的数据
获取到的数据输出


前端小高
536 声望10 粉丝

Hey!