iframe 與 postMessage 方法


iframe 與 postMessage 方法

postMessage 用於跨文檔通信,如父頁面向內嵌的 iframe 發消息。

既是發消息,就有發送方與接收方,發送方要調用 postMessage 方法,接收方要注冊 onmessage 事件處理函數,處理接收的消息。

例:父級頁面向 iframe 頁面發消息

發送方:拿到 iframe 頁面的引用然后調用postMessage 方法:

// 拿到 iframe 中的 window 對象
var wn = document.getElementById('ifrm').contentWindow;
// postMessage 參數: 1.要發送的數據, 2.目標域名
wn.postMessage('Hello to iframe from parent!', 'http://www.example.com');

接收方:注冊 message event handler:

window.addEventListener('message', handleMessage, false);

// 或者
window.onmessage = handleMessage

message event handler 會被傳入一個事件對象,包含以下屬性:

  • data: 發送過來的消息數據
  • origin: 發送方的站點信息(含protocol、hostname、port)
  • source: 發送方的 window 對象引用
// 接收方的 message event handler
function handleMessage(event) {
    // MDN 建議在處理消息前要先檢查發送方的域名,防止惡意消息
    if (event.origin === 'http://www.example.com') {
        // 處理消息
        ...
        // 發送回執給發送方
        event.source.postMessage('Message received', event.origin);
    }
}

子頁面向父頁面發送消息同理:

// 在 iframe 中發送消息
window.parent.postMessage('Hello to parent from iframe!', 'http://www.example.com');

參考

1. Iframes and the postMessage Method

2. Window.postMessage() MDN


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM