網頁端 → 網頁執行APP的方法要導入uni的js
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
如果是vue項目,建議在主頁index.html引入,該JS可以下載到本地使用。
調用方法要寫在下面函數內部(vue項目依舊寫在index.html下面js里)
document.addEventListener('UniAppJSBridgeReady', function() {
uni.getEnv(function(res) {
console.log('當前環境:' + JSON.stringify(res));
});
//向APP發送消息(普通項目)
document.getElementById('aa').onclick=function(){
uni.postMessage({
data: {
action: 'message'
}
});
}
//向APP發送消息(vue項目)
//zhuxiao是隨便起的名字
window.zhuxiao=function(){
//向APP發送消息
uni.postMessage({
data: {
action: 'message'
}
});
}
//vue內部頁面里執行
window.zhuxiao()//寫在觸發方法里
});
//接收APP調用函數,這個如果只是接收,不需要引入JS
function locate(e){
alert(1)
}
uni頁里要用nvue!!!nvue!!!nvue!!!(之前沒注意拖了很久)
<template>
<view class="webview-box">
<web-view ref="webview" class="webview" :src="url" :webview-styles="sty" @message="handleMessage" ></web-view>
</view>
</template>
<script>
export default {
data() {
return {
url:'',
sty:{
progress:{
color:'#3797FC'
}
},
}
},
onLoad(e){
//APP調用網頁關鍵代碼 ,這里我用的$on,可以換成別的觸發方式
var that=this;
uni.$on('dingwei', function(data) {
let currentWebview = getCurrentPages()[0];
that.wv = currentWebview.$getAppWebview();
//調用下面函數
that.handlePostMessage("消息");
})
uni.getSystemInfo({
success: function (res) {
uni.setStorageSync('mtop', res.safeArea.top);
uni.setStorageSync('mleft', res.safeArea.left);
console.log(uni.getStorageSync('mtop'))
}
});
that.url='http://*****?mtop='+uni.getStorageSync('mtop')+'&mleft='+uni.getStorageSync('mleft')+'&token='+uni.getStorageSync('token')
},
methods: {
// 接收h5頁面發來的鍵值判斷需要執行的操作
handleMessage(evt) {
console.log('接收到H5的消息:' + JSON.stringify(evt.detail.data));
return
},
//發送到H5
// 獲取到對應webview(關鍵)通過evalJs(注意大小寫,如果不知道evalJ是什么,可自行百度) 執行網頁的函數,可對其進行傳參,完成與網頁的通訊
handlePostMessage(res) {
console.log(666)
var that=this;
var xx=111+''
var yy=222+''
var str=`locate(JSON.stringify({ "x": `+xx+`, "y": `+yy+`}))`
that.$refs.webview.evalJs(str);
},
}
}
</script>
<style>
.webview-box {
position: absolute;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
.webview {
flex: 1;
}
</style>
