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()中办法名统一 },