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);
  }
相关推荐
JavaGuide39 分钟前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang02171 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户69371750013841 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk81631 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen2 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus2 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing2 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真3 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup3 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法3 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端