前景
项目需求,uniapp嵌入H5页面,并实现通信
uniapp加载本地H5页面
// H5接收webView 传递的信息
const time = setInterval(() => {
if (window.plus) {
clearInterval(time)
const data = JSON.parse(plus.storage.getItem('data'));
console.log('接收的信息', data.ip, data.token, data.mac, data.case_No);
}
}, 10)
//uniapp加载H5页面,并向H5传值
<template>
<view>
<web-view ref="webview" :src="weburl" :update-title=" false"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
weburl: '/static/js/h5.html',
}
},
onLoad(option) {
//获取路由参数
this.ids = JSON.parse(decodeURIComponent(option.ids));
console.log('ids', this.ids)
const data = {
"ip": uni.getStorageSync('IP'),
"token": uni.getStorageSync('token'),
"mac": getMac(),
"case_No": this.case_No,
}
console.log('case_No', this.case_No)
//向H5页面传值
plus.storage.setItem('data', "" + JSON.stringify(data));
},
onShow() {
},
onHide() {
console.log('隐藏')
},
}
</script>
uniapp加载服务器端H5页面
- 通过路由传参url进行传值
- 通过plus.storage.setItem向H5页面进行传参
<template> <web-view id="webview_id" ref="webview" :src="weburl" :update-title=" false"></web-view> </template> <script> export default { data() { return { weburl: '', } }, onLoad(option) {}, onLoad() { // 保持屏幕常亮 uni.setKeepScreenOn({ keepScreenOn: true }) this.timer = setInterval(() => { this.lawIsEnd() }, 1000) }, destroyed() { clearInterval(this.timer) }, methods: { takeJoin() { //从服务器上获取数据信息 const data = { "ip": uni.getStorageSync('IP'), "token": uni.getStorageSync('token'), "mac": getMac(), "case_No": cur_case.case_No, "scene_police": cur_case.scene_police, "web_police1": cur_case.web_police1, "web_police2": cur_case.web_police2, "scene_police_name": cur_case.scene_police_name, "web_police1_name": this.cur_case.web_police1_name, "web_police2_name": res.data.data.web_police2_name, "assist_police": res.data.data.assist_police, "width": wx.getSystemInfoSync().windowWidth, "height": wx.getSystemInfoSync().windowHeight } console.log('data', data) //通过url向H5页面进行传参 this.weburl = 'https://' + uni.getStorageSync('IP') +':8088/players/rtc_video.html?data=' + encodeURIComponent(JSON.stringify(data)) }, lawIsEnd() { //通过plus.storage.setItem向H5页面进行传参 plus.storage.setItem('audioStatus', ""JSON.stringify(res.data.data.audioStatus)); }, } } </script>
//获取路由参数的方法 function getQuery(name) { // 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在) console.log('路径',window.location.search) let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); let r = window.location.search.substr(1).match(reg); console.log(r); if(r != null) { // 对参数值进行解码 return decodeURIComponent(r[2]); } return null; }; //调用获取路由参数(uni-app 传来的值) console.log('传值',getQuery('data')); //监听uniapp,只能在此使用plus.storage.getItem document.addEventListener('UniAppJSBridgeReady', function() { uni.getEnv(function(res) { console.log('当前环境:' + JSON.stringify(res)); }); console.log('传递来的信息') setInterval(function(){ var audioStatus=JSON.parse(plus.storage.getItem('audioStatus')) },1000) })
扫描二维码关注公众号,回复: 15823377 查看本文章
小结
最常用的传值方法还是路由传参,如果还有其他方式,欢迎分享!