uniapp应用和H5页面调取二维码扫描功能
uniapp页面
<template>
<view class="">
<web-view ref="webview" :src="url" @message="handleMessage"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
curWebview: null
}
},
onLoad() {
let that = this
// #ifdef APP-PLUS
setTimeout(() => {
that.curWebview = that.$scope.$getAppWebview().children()[0]
console.log('that.wv', that.curWebview)
}, 800)
// #endif
},
methods:{
handleMessage(e) {
console.log(e)
let that = this
if (e.detail.data && e.detail.data.length > 0) {
let dataInfo = e.detail.data[0]
if (dataInfo.type == 'scanCode') {
uni.scanCode({
success: function(res) {
console.log(res)
if (dataInfo.code && dataInfo.code != '') {
that.curWebview.evalJS(`getData('${res.result}')')`)
} else {
that.curWebview.evalJS(`window.onScanSuc('${res.result}')`)
}
}
})
}
}
}
}
}
<script>
新建js文件
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
return callback(window.WebViewJavascriptBridge);
}
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback);
}
window.WVJBCallbacks = [callback];
const WVJBIframe = document.createElement("iframe");
WVJBIframe.style.display = "none";
WVJBIframe.src = "wvjbscheme://__BRIDGE_LOADED__";
document.documentElement.appendChild(WVJBIframe);
setTimeout(function () {
document.documentElement.removeChild(WVJBIframe);
}, 0);
}
export function installScanQRCode(callBackMethod) {
setupWebViewJavascriptBridge(function (bridge) {
// iOS客户端-扫码回调
bridge.registerHandler("onScanSuc", function (data) {
callBackMethod(data);
});
});
// 安卓客户端-扫码回调
window.onScanSuc = function (data) {
callBackMethod(data);
};
}
export function openAppScanQRCode() {
console.log(window);
let param = {};
param.abID = "test-ScanQrCode";
param.cbFuncName = "onScanSuc";
console.log(window.uni);
if (window.vwtNativeJs) {
console.log("安卓");
window.vwtNativeJs.scanQRCode();
} else if (window.WebViewJavascriptBridge) {
console.log("ios");
console.log(window.WebViewJavascriptBridge);
let list = [];
list.push(param.abID);
list.push(param.cbFuncName);
window.WebViewJavascriptBridge.callHandler("iosScanQRCode", list);
} else if (window.uni) {
window.uni.postMessage({
data: {
type: "scanCode",
},
});
}
}
H5页面
<template>
<div class="img" @click="handleClick">
<img src="@/assets/saomiao.png" alt="" />
<div class="scanIconName">扫描</div>
</div>
</template>
<script>
import { openAppScanQRCode, installScanQRCode } from "@/assets/js/index.js"; //引入上面的js文件
created() {
installScanQRCode((code) => {
this.scanQRCode(code);
});
},
methods:{
scanQRCode(e) {
console.log('二维码获取到的结果',e)
},
handleClick() {
openAppScanQRCode();
},
}
</script>

浙公网安备 33010602011771号