萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

跨域iframe父子頁面通信:postMessage現代方案與兼容性降級實戰

同域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"

解決方案:postMessage 雙向通信

父頁面 parent.html

<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>

子頁面 child.html

<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>

postMessage 核心要點

參數/屬性說明
targetWindow.postMessage(data, targetOrigin)發送消息,targetOrigin限制接收方源,* 為不限制(不安全)
event.data消息內容,任意可序列化對象(結構化克隆算法)
event.origin發送方源(協議+域名+端口),必須驗證
event.source發送方window引用,可回傳消息event.source.postMessage(...)

本地文件協議特殊說明

  • file://協議下,所有頁面origin均為"null"
  • Chrome對null源嚴格阻隔,必須用postMessage
  • 部署到HTTP/HTTPS服務後,同域直接訪問恢復正常

封裝通用通信工具

// 父頁面
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);

安全清單

  1. ✅ 始終驗證event.origin
  2. ✅ 使用JSON.stringify安全序列化,避免函數/循環引用
  3. ✅ 實現請求-響應模式(帶id關聯),支援異步回調
  4. ✅ 內容安全策略Content-Security-Policy: frame-ancestors 'self' trusted.com
copyright © 萬盛學電腦網 all rights reserved