Iframe 父子頁面數據傳遞

發送消息

otherWindow.postMessage(message, targetOrigin, [transfer]);
字段 說明
otherWindow 其他窗口的引用
message 將要發送到其他 window的數據
targetOrigin 通過窗口的origin屬性來指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示無限制)或者一個URI。
transfer 可選,是一串和message 同時傳遞的 Transferable 對象

監聽消息

window.addEventListener("message", receiveMessage, false);

接收的消息屬性:

字段 說明
data 從其他 window 中傳遞過來的對象
origin 調用 postMessage 時消息發送方窗口的 origin
source 對發送消息的窗口對象的引用

安全問題

  • 發送消息要設置具體的 targetOrigin ,防止消息被第三方截獲(例如控制檯手動修改接收方 iframe 的 src 爲第三方,在第三方頁面內做監聽,獲取到消息。)
  • 接收其他網站的message,請始終使用origin和source屬性驗證發件人的身份

實現

父頁面

// 監聽消息
window.addEventListener('message', function (event) {
  // 判斷消息來源
  if (event.origin !== 'xxx') {
    return;
  }
  console.log(event.data)
}, false);

// 給子頁面發送消息
document.getElementById('myIframe').contentWindow.postMessage({ message: '父頁面傳來的消息' }, 'https://xxx.com:8888');

子頁面

// 監聽消息
window.addEventListener('message', function (event) {
  // 判斷消息來源
  if (event.origin !== 'xxx') {
    return;
  }
  console.log(event.data)
}, false);

// 給父頁面發送消息
window.parent.postMessage({ message: '子頁面發來的消息' }, 'https://xxx.com:8888')

whosmeya.com

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章