h5和uniapp通信

混合开发中,uniapp嵌套h5页面的情况下,想进行双方通信,怎么办呢?

uniapp中,整个项目都是写在h5中的,相当于uniapp只是一个壳子,这样开发的话,就可以热更新:

一、h5→uniapp

①h5页面,需要在index.html中引入文件,在使用页面中就可以用postMessage把信息传过去。 index.html

js 复制代码
<script type="text/javascript" src="./src/utils/uniwebview.js"></script>
<script>
document.addEventListener('UniAppJSBridgeReady', function() {
  uni.webView.getEnv(function(res) {
    console.log('当前环境:' + JSON.stringify(res));
  });
});

</script>

②h5使用页面:

js 复制代码
const onPrint = async (item) => {
  const imageAddress = await projectApi.getPayQR(item.id);
  
  uni.postMessage({
    data: {
      code: '5',
      info: item.producerName,
      time: dayjs().format('YYYY-MM-DD HH:mm'),
      imageAddress: imageAddress,
    }
  });
}

③uniapp页面,在backMeaasge中获得h5传递过来的信息 h5→uniapp

js 复制代码
<template>
  <view class="content">
   <web-view   
      src="http://192.168.xx.xxx:3000"
      @message="backMessage"
    ></web-view>
  </view>
  
</template>

<script>
      backMessage(event) {
        console.log('h5传回来的----', event.detail.data[0].code);
        if(event.detail.data[0].code === 5) {
          console.log('打印了', event.detail.data[0].info)
        }
      },
</script>

二、uniapp→h5

①uniapp中,

js 复制代码
    const currentWebview = that.$scope.$getAppWebview();
    const html = currentWebview.children()[0];
    html.evalJS(`blueresult(${JSON.stringify(list[i])})`);

②h5中,uniapp中的evalJs中的名字和window.后面的名字要一致。

js 复制代码
window.blueresult = function(device) {
    deviceList.value.push(device)
    console.log("蓝牙传设备回来了:", deviceList.value);
  }
相关推荐
a1117768 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得08 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
行走的陀螺仪10 小时前
uni-app + Vue3编辑页/新增页面给列表页传参
前端·vue.js·uni-app
We་ct11 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
2301_8127314111 小时前
CSS3笔记
前端·笔记·css3
ziblog11 小时前
CSS3白云飘动动画特效
前端·css·css3
越努力越幸运50811 小时前
CSS3学习之网格布局grid
前端·学习·css3
半斤鸡胗12 小时前
css3基础
前端·css
ziblog12 小时前
CSS3创意精美页面过渡动画效果
前端·css·css3
akangznl12 小时前
第四章 初识css3
前端·css·css3·html5