APP 局部
<template>
<view class="box">
<web-view :src="getRouter" ref="videoWebView" id="videoWebView"
@message="handleMessage"></web-view>
</view>
</template>
<script>
import {mapGetters,mapMutations} from 'vuex'
export default {data() {
return {wv: null};
},
computed:{...mapGetters(['user','token','openid']),
getRouter:function(){
let url =''
url = `http://192.168.3.131:8001/`
return url
}
},
methods:{...mapMutations(['SET_INDEX']),
handleMessage:function(e){//app 接管到 h5 内容传来的信息
let data=e.detail.data[0]
},
h5Message:function(e){// H5 接管到 H5 内容传来的信息(uni 中 h5 中应用 webview 嵌套 h5 时)let data=e.data.data
if(data.name && data.name==="postMessage"){data=data.arg}else{return}
},
sendMessageH5:function(){
let that=this
let params=that.encodeParams({token:that.token,openid:that.openid})
that.wv.evalJS(`savaParams("${params}")`)
// 此处 双引号为重点,被坑一小时!!!}
},
onShow:function(){
let that=this
if(that.wv){// 页面切换时 从新发送音讯
that.sendMessageH5()}
},
onReady:function(){
let that = this;
// #ifdef H5
//H5 接管音讯办法
window.addEventListener("message", this.h5Message, false)
// #endif
// #ifdef APP-PLUS
// App 初始化拿到 webView 进行发送音讯
var currentWebview = that.$scope.$getAppWebview()
that.$nextTick(()=>{that.wv = currentWebview.children()[0]
that.sendMessageH5()})
// #endif
},
onUnload:function(){
// #ifdef H5
window.removeEventListener("message", this.h5Message, false)
// #endif
}
}
</script>
H5 局部 (uni 打包的 H5)
main.js 中
import Vue from 'vue'
import webUni from '@/static/js/webview.js'
// 此处用的是 uni 提供的 https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js
// 有重大 bug 须要批改 js
Vue.prototype.$webUni=webUni
H5 局部(webview.js 中)
格式化后大概 182 行,
原代码:var E = “undefined” != typeof uni ? uni: {};
批改为:var E = “undefined” != typeof webUni ? webUni: {};
否则默认导出会找不到 uni , 被框架笼罩!!!
对应页面中:
methods:{sendMessage:function(){
this.$webUni.postMessage({
data:{
type:'swichTab',
index:0,
id:0,
path:'/pages/tabbar/index'
}
})
}
}
H5 接管 app 传递的音讯
App.js 中
methods: {...mapMutations(['SET_TOKEN','SET_OPENID']),
savaParams:function(params){
// 解决传递的信息
let query=this.decodeParams(params)
this.SET_TOKEN((query.token||''))
this.SET_OPENID((query.openid||''))
}
},
onLaunch: function(options) {
let that=this
window.savaParams=that.savaParams
//window 挂载的办法与 app evalJS() 中办法名统一},