1. iframe传值到父页面
//被嵌入的iframe页面 向父vue页面发送信息
window.parent.postMessage({
data: {
code:"success",
token:token
}
}, '*');
//父页面接受iframe的值
methods: {
//获取iframe页面里的token
handleMessage (event) {
const data = event.data.data
if(data.code === "success"){
let token=data.token;
this.$store.commit('setToken',token)//存储token到vuex
sessionStorage.setItem('token',token);
this.getuserInfo()
}
},
}
mounted() {
//监听子页面的事件
window.addEventListener('message', this.handleMessage);
},
2.父页面传值到iframe
async mounted() {
var that = this
//监听webview页面的事件
window.addEventListener('message', this.handleMessage);
console.log(document.getElementsByTagName('iframe'));
this.iframe=document.getElementsByTagName('iframe')[0];
this.iframe.onload = function(){ //确保iframe加载成功
that.postMsg()
}
},
//传值给iframe
methods: {
postMsg() {
let token=sessionStorage.getItem('token');
this.$refs.iframe.contentWindow.postMessage({
code: 'success',
token:token,
userInfo:this.$store.state.userInfo,
}, '*')
},
}
//iframe接受父页面传过来的值
//获取嵌入的父页面传过来的数据
handleMessage (event) {
const data = event.data;
if (data.hasOwnProperty('wappalyzer')) { //无消息时
return
}else if (data.type=='webpackClose') { //关闭时
return
}else if (data.hasOwnProperty('token')) { //有值时
this.$store.commit("$_setToken", data.token);
sessionStorage.setItem("token", data.token);
const userInfo=data.userInfo;
this.$store.state.username = userInfo.username;
this.$store.state.avatarUrl = userInfo.avatarUrl;
}
},
mounted() {
window.addEventListener('message',this.handleMessage);
}