uni-app 与 web-view内嵌网页双向通信

主要是实现内嵌网页发送命令调用App内扫码功能,App将扫码结果返回至内嵌网页内进行展示。

一、内嵌网页向uniapp通信

在内嵌网页(vue2)内引入“uni.webview.1.5.1.js”,点击扫码按钮调用postMessage方法。

代码如下(示例):

<template>
    <div>
        <a-button @click="handleClick">点击按钮</a-button>
    </div>
</template>

<script>
import webUni from '/src/utils/uni.webview.1.5.1.js';
export default {
    data() {
        return {
            scanList: []
        };
    },
    mounted() {
        let that = this;
        //接收消息
        window.msgFromUniapp = function (arg) {
            console.log(arg,'获取扫码数据');
            this.scanList.push(arg);
        };
    },
    methods: {
        //点击发送消息
        handleClick(event) {
            webUni.postMessage({
                data: {
                    msg: '扫码'
                }
            });
        },
    }
};
</script>

二、Uniapp向内嵌网页通信

代码如下(示例):

<template>
  <view class="container">
    <web-view :webview-styles="{width: '100%', height: '100%'}" :src="targetUrl" 
         @message="handleMessage" ></web-view>
  </view>
</template>

<script setup>
  import { ref } from 'vue';
  import { onLoad } from "@dcloudio/uni-app";
  var targetUrl = ref('')
  var token = uni.getStorageSync("token")
  onLoad((options) => {
    if (options.url) {
      targetUrl.value = options.url + `?token=${token}`;
    }
  })
  const vw = ref(null);
  const pages = getCurrentPages();
  //接收消息
  const handleMessage = (e) => {
    vw.value = pages[pages.length - 1].$getAppWebview().children()[0];
    console.log(e.detail.data[0].msg, '-father-event')   
    if (e.detail.data[0].msg) {
      uni.scanCode({
        success: function(res) {
          sendMessage(res.result)
        }
      });
    }
  }
  //发送消息
  const sendMessage = (val) => {
    const _funName = 'msgFromUniapp'
    vw.value.evalJS(`${_funName}(${JSON.stringify(val)})`);
  }
</script>

<style>
  .container {
    background: #ffffff;
    width: 100%;
    
    height: 100%;
    border: 1px solid red;
    /* overflow: hidden; */
  }

  .frame {
    width: 100%;
    height: calc(100% - var(--status-bar-height) - 100rpx);
  }
</style>

该处对页面代码进行了删减,具体可根据自己的应用进行补充!!


总结

以上就是今天要讲的内容,本文仅仅简单介绍了uni-app 与 web-view内嵌网页的双向通信,感谢支持!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值