Vue?使用postMessage?實現(xiàn)父子跨域通信
一、跨域通信
1.子向父通信
parent.html
// 頁面銷毀前,務(wù)必去除監(jiān)聽器,否則會造成資源泄露!
beforeDestory () {
window.removeEventListener('message', this.listenerFun)
}
mounted() {
window.addEventListener('message',this.listenerFun)
}
methods: {
listenerFun (e) {
console.log(e.data);
if(e.data.msg==='xxx'){
// 業(yè)務(wù)處理邏輯
}
}
}child.html
window.parent.postMessage({ msg:"xxx"},'*');2.父向子通信
parent.html
var myframe = document.getElementById('myframe') //獲取iframe
myframe.contentWindow.postMessage({data:'parent'}, childDomain);//childDomain是子頁面的源(協(xié)議+主機+端口號)child.html
window.addEventListener('message', function(e){
console.log(e.data.data);
})注意:
- 子向父,子
postMessage,父監(jiān)聽message; - 父向子,父
postMessage,子監(jiān)聽message; - 測試發(fā)現(xiàn),子向父
postMessage的時候,源可以寫為‘*’,父向子postMessage的時候,源需要寫成子的源,(也就是子頁面的協(xié)議+主機號+端口);
二、示例
parent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe父級頁面</title>
<style>
* {
padding: 0;
margin: 0;
}
iframe {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<h2>我是父級頁面</h2>
<button id='btn'>父頁面的按鈕</button>
<div id="default">div內(nèi)容</div>
<iframe src="http://localhost:8800/child.html" frameborder="0" name='myframe' id='myframe'></iframe>
<script language="javascript" type="text/javascript">
window.addEventListener('message',function(e){
console.log(e.data);
if(e.data.msg==='hideselfService'){
document.getElementById('default').style.display = 'none';
}
});
document.getElementById('btn').onclick= function(){
var myframe = document.getElementById('myframe');
myframe.contentWindow.postMessage({data:'parent'},'http://localhost:8800');
}
</script>
</body>
</html>child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe子頁面</title>
</head>
<body>
<h2>我是內(nèi)嵌的子頁面</h2>
<button id='btn'>子頁面的按鈕</button>
<script>
document.getElementById('btn').onclick= function(){
window.parent.postMessage({
msg:"hideselfService"
},'*');
}
window.addEventListener('message', function(e){
console.log(e.data.data);
})
</script>
</body>
</html>三、拓展閱讀
《Vue進階(九十五):addEventListener() 事件監(jiān)聽》
知識點擴展
vue項目中postMessage的使用總結(jié)
postMessage簡介
window.postMessage() 方法可以安全地實現(xiàn)跨源通信。通常,對于兩個不同頁面的腳本,只有當執(zhí)行它們的頁面位于具有相同的協(xié)議(通常為https),端口號(443為https的默認值),以及主機 (兩個頁面的模數(shù) Document.domain設(shè)置為相同的值) 時,這兩個腳本才能相互通信。window.postMessage() 方法提供了一種受控機制來規(guī)避此限制,只要正確的使用,這種方法就很安全。
從廣義上講,一個窗口可以獲得對另一個窗口的引用(比如 targetWindow = window.opener),然后在窗口上調(diào)用 targetWindow.postMessage() 方法分發(fā)一個 MessageEvent 消息。接收消息的窗口可以根據(jù)需要自由處理此事件 (en-US)。傳遞給 window.postMessage() 的參數(shù)(比如 message )將通過消息事件對象暴露給接收消息的窗口。
詳情鏈接:postMessage
項目搭建
創(chuàng)建兩個vue項目
- 項目一:iframe-test-father;
- 項目二:iframe-test-son
iframe-test-father 組件代碼
<template>
<div id="nav">
<div>{{ childMsg }}</div>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<button @click="handleClickFatherToSon">父傳子</button>
<iframe
ref="iframeRef"
id="iframe"
src="http://localhost:8080/#/"
frameborder="0"
></iframe>
</div>
<router-view />
</template>
<script>
export default {
data() {
return {
iframeWin: null,
childMsg: "",
count: 1,
};
},
mounted() {
// this.iframeWin = this.$refs.iframeRef.contentWindow;
// this.iframeWin = document.getElementById("iframe").contentWindow;
window.addEventListener("message", this.handleMessage);
},
methods: {
handleMessage(event) {
const data = event.data.data;
if (data) {
if (data.code == "success") {
// alert(data.test);
this.childMsg = data.test;
}
}
},
handleClickFatherToSon() {
this.count += 1;
document.getElementById("iframe").contentWindow.postMessage(
{
data: {
code: "success",
test: "我是父頁面數(shù)據(jù)" + this.count,
},
},
"*"
);
// this.iframeWin.postMessage(
// {
// data: {
// code: "success",
// test: "我是父頁面數(shù)據(jù)" + this.count,
// },
// },
// "*"
// );
},
},
};
</script>iframe-test-son組件代碼
<template>
<div class="home">test1-home</div>
<div>{{ fatherMsg }}</div>
<button @click="handleClick">傳遞數(shù)據(jù)</button>
</template>
<script>
export default {
name: "Home",
data() {
return {
fatherMsg: "",
};
},
mounted() {
window.addEventListener("message", this.handleClickMessage);
},
methods: {
handleClick() {
window.parent.postMessage(
{
data: {
code: "success",
test: "我是子頁面數(shù)據(jù)",
},
},
"*"
);
},
handleClickMessage(event) {
if (event.data.type != "webpackOk") {
const data = event.data.data;
if (data.code == "success") {
this.fatherMsg = data.test;
}
}
},
},
};
</script>
效果圖

遺留bug

bug :Uncaught DOMException: Blocked a frame with origin “http://localhost:8082” from accessing a cross-origin frame.
到此這篇關(guān)于Vue應(yīng)用 postMessage 實現(xiàn)父子跨域通信的文章就介紹到這了,更多相關(guān)Vue父子跨域通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-cil之a(chǎn)xios的二次封裝與proxy反向代理使用說明
這篇文章主要介紹了vue-cil之a(chǎn)xios的二次封裝與proxy反向代理使用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue.js構(gòu)建你的第一個包并在NPM上發(fā)布的方法步驟
這篇文章主要介紹了Vue.js構(gòu)建你的第一個包并在NPM上發(fā)布的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05
Vue動態(tài)構(gòu)建混合數(shù)據(jù)Treeselect選擇樹及巨樹問題的解決
這篇文章主要介紹了Vue動態(tài)構(gòu)建混合數(shù)據(jù)Treeselect選擇樹及巨樹問題的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
Vue3中各種靈活傳遞數(shù)據(jù)的方式小結(jié)
Vue 3 提供了多種數(shù)據(jù)傳遞的方式,讓我們的組件之間可以盡情地交流,接下來,我們就直接一個個來看,這些方式都是怎么工作的,感興趣的小伙伴跟著小編一起來看看吧2024-07-07

