实践:uniapp中webview内置网页与app实时通讯
uniapp使用webview内置网页与app实时通讯
·
目录
5、到此uniapp使用webview内置网页与app通讯就实现了
1、uniapp官网webview地址
2、uniapp中vue文件代码
uniapp通过路由传值给网页
<template>
<view class="content" style="z-index: 9999999;">
<view class="status-bar"></view>
<web-view :src="htmlUrl" @message="handleMessage"></web-view>
</view>
</template>
<script>
var wv = null;
export default {
data() {
return {
htmlUrl: getApp().globalData.webUrl + "/#/dcim-device-map?token=" + uni.getStorageSync('lifeData').token +
"&refreshToken=" + uni.getStorageSync("refreshToken") + "&expiresIn=" + uni.getStorageSync(
"expiresIn")
}
},
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: 25
})
}, 1000); //如果是页面初始化调用时,需要延时一下
// #endif
},
mounted() {
// 强制横屏
plus.screen.lockOrientation('landscape-primary');
console.log(this.htmlUrl)
},
methods:{
handleMessage(res){
console.log("成功接收到网页传的消息:",res)
}
},
// 监听返回键
onBackPress() {
if (wv != "" && wv != null) {
wv.close();
wv = null;
}
uni.$u.route({
type: 'redirect',
url: 'pages/home/index'
})
},
beforeDestroy() {
plus.screen.lockOrientation('portrait-primary');
if (wv != "" && wv != null) {
wv.close();
wv = null;
}
}
}
</script>
<style scoped>
body,
html {
background-color: rgb(0, 19, 39);
}
.status-bar {
height: var(--status-bar-height);
min-height: var(--status-bar-height);
width: 100%;
}
.content {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: rgb(0, 19, 39);
}
</style>
3、webview链接的远程网页代码
<template>
<div class="overview">
<!--更换空间-->
<el-row>
<el-col :lg="8" :md="8" :sm="8" :xl="8" :xs="8" style="text-align: right">
<div style="line-height: 40px;vertical-align: center;margin-right: 1.3vw" @click="closeMapToDcimApp">
<img src="../../../assets/images/dcim_app_h5/mapBack.png">
<a class="pointer text-white" style="margin-left: 5px;">退出地图</a>
</div>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
name: "Overview",
data() {
return {
};
},
methods: {
// 退出地图
closeMapToDcimApp() {
this.$confirm('确定要退出地图地图吗?', {
cancelButtonText: '取消',
confirmButtonText: '确定',
callback: action => {
if (action === 'confirm') {
// eslint-disable-next-line no-undef
uni.postMessage({
data: {
name:"小明",
age:"20"
},
})
}
}
})
}
}
}
</script>
<style scoped>
</style>
4、vue引入uniapp的JS
<script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script>
最新uniapp JS以官方文档为准
5、到此uniapp使用webview内置网页与app通讯就实现了
更多推荐
已为社区贡献2条内容
所有评论(0)