同域iframe父子通信可直接訪問window.parent/contentWindow,但跨域(協議/域名/端口任一不同)受同源策略阻隔。本文實戰記錄:本地文件協議file://下Chrome報錯Blocked a frame with origin "null",採用HTML5postMessage實現跨域安全通信,並提供特性檢測降級策略。
// 子頁面 child.html var t = window.parent; t.ParentFunction(); // Chrome file:// 協議報錯:Blocked a frame with origin "null"
<script>
// 1. 定義業務方法
function ParentFunction() { alert('父頁面方法被調用'); }
// 2. 監聽消息
function receiveMessage(event) {
// 生產環境必須驗證來源!
// if (event.origin !== 'https://trusted-domain.com') return;
if (event.data === 'call:ParentFunction') {
ParentFunction();
}
}
// 3. 兼容性綁定
if (window.addEventListener) {
window.addEventListener('message', receiveMessage, false);
} else if (window.attachEvent) { // IE8
window.attachEvent('onmessage', receiveMessage);
}
</script>
<iframe id="FRMdetail" src="child.html"></iframe>
<script>
$('#btnTest').click(function() {
var parentWin = window.parent;
// 特性檢測:同域可直接調用
if (typeof parentWin.ParentFunction === 'function') {
parentWin.ParentFunction();
}
// 跨域/受限環境:postMessage
else {
parentWin.postMessage('call:ParentFunction', '*');
// 生產環境指定具體目標源:'https://parent-domain.com'
}
});
</script>
| 參數/屬性 | 說明 |
|---|---|
targetWindow.postMessage(data, targetOrigin) | 發送消息,targetOrigin限制接收方源,* 為不限制(不安全) |
event.data | 消息內容,任意可序列化對象(結構化克隆算法) |
event.origin | 發送方源(協議+域名+端口),必須驗證 |
event.source | 發送方window引用,可回傳消息event.source.postMessage(...) |
file://協議下,所有頁面origin均為"null"null源嚴格阻隔,必須用postMessage// 父頁面
const IframeMessenger = {
init(handlerMap) {
window.addEventListener('message', e => {
if (e.origin !== location.origin) return; // 同域驗證
const { action, payload, id } = e.data;
if (handlerMap[action]) {
Promise.resolve(handlerMap[action](payload))
.then(res => e.source.postMessage({ id, result: res }, e.origin));
}
});
}
};
// 子頁面
function callParent(action, payload) {
return new Promise((resolve) => {
const id = Math.random().toString(36).slice(2);
const handler = (e) => {
if (e.data.id === id) {
window.removeEventListener('message', handler);
resolve(e.data.result);
}
};
window.addEventListener('message', handler);
window.parent.postMessage({ action, payload, id }, '*');
});
}
// 使用
callParent('ParentFunction', {}).then(console.log);
event.originJSON.stringify安全序列化,避免函數/循環引用id關聯),支援異步回調Content-Security-Policy: frame-ancestors 'self' trusted.com