uniapp APP内部与网页通讯,互相执行对方方法

网页端  → 网页执行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>

posted on 2021-12-13 17:30  Just丶随心  阅读(1802)  评论(0编辑  收藏  举报

导航