h5页面
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>h5网页</title>
</head>
<style>
.btn {
margin-top: 400px;
}
</style>
<body>
<button class="btn" type="button" id="postMessage">网页向应用发送消息</button>
</body>
<script src="./uni.webview.1.5.3.js"></script>
<script>
// 待触发 `UniAppJSBridgeReady` 事件后,即可调用 uni 的 API。
document.addEventListener('UniAppJSBridgeReady', function() {
uni.postMessage({
data: {
action: 'message'
}
});
uni.getEnv(function(res) {
console.log('当前环境:' + JSON.stringify(res));
});
document.getElementById('postMessage').addEventListener('click', function() {
console.log('点击')
uni.postMessage({
data: {
action: 'message'
}
});
});
});
</script>
</html>
uniapp页面
<template>
<view>
<web-view @message="handlePostMessage" src="/hybrid/html/index.html"></web-view>
</view>
</template>
<script>
var wv; //计划创建的webview
export default {
data() {
return {
}
},
onReady() {
// #ifdef APP-PLUS
// var currentWebview = this.$scope
// .$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
// setTimeout(function() {
// wv = currentWebview.children()[0]
// wv.setStyle({
// top: 150,
// height: 300
// })
// }, 1000); //如果是页面初始化调用时,需要延时一下
// #endif
},
methods: {
handlePostMessage(data) {
console.log("接收到消息:" + JSON.stringify(data.detail));
//实时接收消息,通过判断接收到的消息内容执行不同方法
}
}
};
</script>
备注
h5页面如果引用本地的页面需要放在根目录(如图位置),
uni.webview.1.5.3.js在uniapp官网下载官方网址