UniApp:微信小程序下webView嵌入H5通信

[!IMPORTANT]
UniApp:web-view文档
UniApp官方提供的sdk会导出uni实例,引入后会覆盖原有 uni 实例,以下版本sdk已经改为导出 webUni
修改后的SDK:uni-webview-js-1.5.5

1. UniApp-微信小程序页面

<template>
  <view>
    <web-view v-if="webSite" :src="webSite" @message="onMessage" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      webSite: ''
    }
  },
  methods: {
    onMessage(e) {
      console.log('onMessage  e:', e)
    },
    async pageInit(options) {
      const pageUrl = options?.page
      options?.page && (this.webSite = decodeURIComponent(pageUrl))
    }
  },
  async onLoad(query) {
    this.pageInit(query)
  }
}
</script>

2. UniApp-H5页面

2.1 根目录下 index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <!-- 微信小程序兼容 -->
  <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
  <!-- uni.webview.1.5.5.js -->
  <!-- UniApp官方提供的sdk引入后会覆盖uni实例,以下版本sdk已经改为webUni -->

  <script type="module" src="./static/uni-webview-js-1.5.5/index.js"></script>
  <title></title>
</head>

<body>
  <div id="app"><!--app-html--></div>
  <script type="module" src="/src/main.ts"></script>
</body>

</html>

2.2 vue页面调用

<template>
  <view>即将跳转...</view>
</template>

<script lang="ts" setup>
declare var webUni: any
onLoad(() => {
  console.log('onLoad  webUni:', webUni)
  // 网页向应用 postMessage 时,会在特定时机(后退、组件销毁、分享)触发并收到消息。
  webUni.postMessage({
    data: {
      active: 'TERMINAL_WEB_MESSAGE'
    }
  })
  // 可以操作webview页面的跳转等操作,详细信息:2.1 打印结果
  webUni.webView.navigateBack({ delta: 1 })
})
</script>

3. 普通H5页面

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <!-- 微信小程序兼容 -->
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <!-- uni.webview.1.5.5.js -->
    <!-- UniApp官方提供的sdk引入后会覆盖uni实例,以下版本sdk已经改为webUni -->
    <script type="module" src="https://mtdsosscdn.oppein.com/MTDS/sale-tool-frontend/uni-pulgins/uni-webview-js%401.5.5/index.js"></script>
    <title>网络网页</title>
  </head>
  <body>
    <script type="text/javascript">
      // 待触发 `UniAppJSBridgeReady` 事件后,即可调用 uni 的 API。
      document.addEventListener('UniAppJSBridgeReady', function() {
        console.log('onLoad  webUni:', webUni)
        // 网页向应用 postMessage 时,会在特定时机(后退、组件销毁、分享)触发并收到消息。
        webUni.postMessage({
          data: {
            active: 'TERMINAL_WEB_MESSAGE'
          }
        })
        // 可以操作webview页面的跳转等操作,详细信息:2.1 打印结果
        webUni.webView.navigateBack({ delta: 1 })
      });
    </script>
  </body>
</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。