主要是实现内嵌网页发送命令调用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内嵌网页的双向通信,感谢支持!!!
5891

被折叠的 条评论
为什么被折叠?



