Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

HTML5 postMessage 跨窗口數據交換完全指南

前言

前面我們講過用 script 標籤(jsonp)以及 iframe 標籤(window.name、location.hash)來跨域交換數據,這次換 HTML5 的 postMessage 登場。與前幾種方式最大的不同是:postMessage 無法與服務端交換數據,只能在兩個窗口(iframe)之間傳遞。廢話不多說,直接進入實戰。

postMessage 實戰

postMessage 是給兩個窗口用的。你可能會想:同時開著百度和谷歌,是不是就能互相通信了?並非如此。兩個窗口能通信的前提是:其中一個以 iframe 形式存在於另一個之中,或是由另一個透過 window.open()、超連結打開(此時可用 window.opener 拿到源窗口)。也就是說,你必須能取得目標窗口(target window)的引用,否則毫無關聯的兩個窗口根本無從通信。

身為 H5 家族的一員,postMessage 的瀏覽器支持度相當不錯。它的用法也很簡單:

otherWindow.postMessage(message, targetOrigin, [transfer]);

其中 otherWindow 是接收方窗口的引用,常見來源有:

window.frames[0].postMessage
document.getElementsByTagName('iframe')[0].contentWindow
window.opener.postMessage
event.source.postMessage
window.open 返回的引用 ...

message 顧名思義是要發送的數據,幾乎支持字串、數字、JSON 等所有形式(可參考 structured clone algorithm);targetOrigin 是接收方的 URI(協議+主機+端口),也可寫成完整 url(後續路徑會被忽略),用通配符 * 可放寬到所有域,但基於安全強烈不建議;transfer 可省略。

接收方則透過監聽 message 事件來取數據,詳見下例。

window 與 iframe 之間

假設 index 頁面有個不同源的 iframe,我們要給它發數據,而 iframe 收到後再回傳一句「我收到了」:

<!-- https://localhost:81/fish/index.html -->
<script type="text/javascript">
// 頁面加載完後才能取到 iframe 節點
window.onload = function(){
  // 向目標源發送數據
  document.getElementsByTagName('iframe')[0].contentWindow
    .postMessage({"age":10}, 'https://localhost:8080');
};
// 監聽是否有數據發來
window.addEventListener('message', function(e) { console.log(e); });
</script>
<iframe src="https://localhost:8080/index.html"></iframe>
<!-- https://localhost:8080/index.html -->
<script type="text/javascript">
window.addEventListener('message', function(e){
  // 判斷來源是否可靠
  if(e.origin !== 'https://localhost:81') return;
  console.log(e);
  // 回發數據
  e.source.postMessage('hello world', e.origin);
}, false);
</script>

事件對象 e 上有三個最重要的屬性:data 是傳輸的數據;origin 是發送方的源(協議+主機+端口);source 則引用發送消息的窗口對象,可用於回傳。接收端建議用 addEventListener 監聽 message(若要兼容老 IE 需用 attachEvent),不推薦 window.onmessage,因其兼容性欠佳。

window 與 window 之間

再來看兩個獨立窗口的通信。用 window.open() 打開新窗口後,若兩者同源,可直接用 window.opener.functionName 互相調用;若不同源,過去會寸步難行,而 H5 的 postMessage 讓 window.opener.postMessage() 不再報錯:

<!-- https://localhost:81/fish/index.html -->
<script type="text/javascript">
var popup = window.open('https://localhost:8080/index.html');
// 待彈窗完全加載後再發送(若未被攔截)
setTimeout(function() {
  popup.postMessage({"age":10}, 'https://localhost:8080');
}, 1000);
</script>
<!-- https://localhost:8080/index.html -->
<script type="text/javascript">
window.addEventListener('message', function(e) {
  console.log(e);
  // console.log(e.source === window.opener); // true
});
</script>

這裡之所以用定時器,是因為發送方必須等目標窗口完全加載、監聽器就緒後,數據才會被接收到,而加載耗時不定,delay 值也難以拿捏。更可靠的作法是:目標頁加載完成後主動 postMessage 通知源頁,源頁收到後再回發數據。

安全顧慮

談到跨域,難免要問一句:安全嗎?對 postMessage 而言,答案是肯定的。它採用「雙向安全機制」:發送方會指定接收方的源(所以別用 *),接收方也能用 event.origin 驗證來源是否可信。

Copyright © Linux教程網 All Rights Reserved