由于同源策略存在,javascript 的跨域一直都是一個(gè)棘手的問題
父頁面無法直接獲取 iframe 內(nèi)部的跨域資源;同時(shí),iframe 內(nèi)部的跨域資源也無法將信息直接傳遞給父頁面
下面我來簡單介紹下父子之間通信的方式, 以 Vue 項(xiàng)目為例
父傳子
- 父頁面
<template>
<div class="test">
<!-- 通過 iframe 嵌入子頁面 -->
<iframe ref="iframe" src="http://localhost:8082/#/home"></iframe>
</div>
</template>
<script>
export default {
mounted() {
let iframe = this.$refs.iframe;
// 必須等 iframe 加載完畢后再發(fā)送消息,否則子頁面接收不到數(shù)據(jù)
iframe.onload = () => {
// 通過 postMessage(data, 子頁面協(xié)議+域名+端口號) 發(fā)送數(shù)據(jù)
iframe.contentWindow.postMessage({
name: 'wells'
}, 'http://localhost:8082');
}
}
};
</script>
- 子頁面
<script>
export default {
mounted() {
// 接收父頁面?zhèn)鬟f的數(shù)據(jù)
window.addEventListener('message', evt => {
// 判斷是否為父頁面?zhèn)鬟^來的
if (evt.origin !== 'http://localhost:8080') return;
console.log(evt.data); // {name: 'wells'}
}, false);
}
};
</script>
子傳父
- 子頁面
<script>
export default {
mounted() {
// 通過 postMessage(data, 子頁面協(xié)議+域名+端口號) 發(fā)送數(shù)據(jù)
window.parent.postMessage({
age: 24
}, 'http://localhost:8080');
}
};
</script>
- 父頁面
<template>
<div class="test">
<!-- 通過 iframe 嵌入子頁面 -->
<iframe ref="iframe" src="http://localhost:8082/#/home"></iframe>
</div>
</template>
<script>
export default {
mounted() {
// 接收子頁面?zhèn)鬟f的數(shù)據(jù)
window.addEventListener('message', evt => {
// 判斷是否為子頁面?zhèn)鬟^來的
if (event.origin !== 'http://localhost:8082') return;
console.log(evt.data); // {age: 24}
}, false);
}
};
</script>