Vue?使用postMessage?實(shí)現(xiàn)父子跨域通信
一、跨域通信
1.子向父通信
parent.html
// 頁面銷毀前,務(wù)必去除監(jiān)聽器,否則會(huì)造成資源泄露!
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é)議+主機(jī)+端口號(hào))child.html
window.addEventListener('message', function(e){
console.log(e.data.data);
})注意:
- 子向父,子
postMessage,父監(jiān)聽message; - 父向子,父
postMessage,子監(jiān)聽message; - 測(cè)試發(fā)現(xiàn),子向父
postMessage的時(shí)候,源可以寫為‘*’,父向子postMessage的時(shí)候,源需要寫成子的源,(也就是子頁面的協(xié)議+主機(jī)號(hào)+端口);
二、示例
parent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe父級(jí)頁面</title>
<style>
* {
padding: 0;
margin: 0;
}
iframe {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<h2>我是父級(jí)頁面</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進(jìn)階(九十五):addEventListener() 事件監(jiān)聽》
知識(shí)點(diǎn)擴(kuò)展
vue項(xiàng)目中postMessage的使用總結(jié)
postMessage簡(jiǎn)介
window.postMessage() 方法可以安全地實(shí)現(xiàn)跨源通信。通常,對(duì)于兩個(gè)不同頁面的腳本,只有當(dāng)執(zhí)行它們的頁面位于具有相同的協(xié)議(通常為https),端口號(hào)(443為https的默認(rèn)值),以及主機(jī) (兩個(gè)頁面的模數(shù) Document.domain設(shè)置為相同的值) 時(shí),這兩個(gè)腳本才能相互通信。window.postMessage() 方法提供了一種受控機(jī)制來規(guī)避此限制,只要正確的使用,這種方法就很安全。
從廣義上講,一個(gè)窗口可以獲得對(duì)另一個(gè)窗口的引用(比如 targetWindow = window.opener),然后在窗口上調(diào)用 targetWindow.postMessage() 方法分發(fā)一個(gè) MessageEvent 消息。接收消息的窗口可以根據(jù)需要自由處理此事件 (en-US)。傳遞給 window.postMessage() 的參數(shù)(比如 message )將通過消息事件對(duì)象暴露給接收消息的窗口。
詳情鏈接:postMessage
項(xiàng)目搭建
創(chuàng)建兩個(gè)vue項(xiàng)目
- 項(xiàng)目一:iframe-test-father;
- 項(xiàng)目二: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">父?jìng)髯?lt;/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 實(shí)現(xiàn)父子跨域通信的文章就介紹到這了,更多相關(guān)Vue父子跨域通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue與django集成打包的實(shí)現(xiàn)方法
這篇文章主要介紹了vue與django集成打包的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
vue-cil之a(chǎn)xios的二次封裝與proxy反向代理使用說明
這篇文章主要介紹了vue-cil之a(chǎn)xios的二次封裝與proxy反向代理使用說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue.js構(gòu)建你的第一個(gè)包并在NPM上發(fā)布的方法步驟
這篇文章主要介紹了Vue.js構(gòu)建你的第一個(gè)包并在NPM上發(fā)布的方法步驟,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05
Vue動(dòng)態(tài)構(gòu)建混合數(shù)據(jù)Treeselect選擇樹及巨樹問題的解決
這篇文章主要介紹了Vue動(dòng)態(tài)構(gòu)建混合數(shù)據(jù)Treeselect選擇樹及巨樹問題的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
Vue3中各種靈活傳遞數(shù)據(jù)的方式小結(jié)
Vue 3 提供了多種數(shù)據(jù)傳遞的方式,讓我們的組件之間可以盡情地交流,接下來,我們就直接一個(gè)個(gè)來看,這些方式都是怎么工作的,感興趣的小伙伴跟著小編一起來看看吧2024-07-07
簡(jiǎn)單聊一聊axios配置請(qǐng)求頭content-type
最近在工作中碰到一個(gè)問題,后端提供的get請(qǐng)求的接口需要在request header設(shè)置,下面這篇文章主要給大家介紹了關(guān)于axios配置請(qǐng)求頭content-type的相關(guān)資料,需要的朋友可以參考下2022-04-04

