[TOC]
* * * * *
>跨文檔消息傳送(cross-document messaging),有時候簡稱 XDM,指的是來自不同域的頁面間傳遞消息。
* * * * *
### 邏輯描述
~~~
1.先取得消息要發送的目的文檔的 window 引用
iframe
var frame=document.getElementById('frame').contentWindow;
js 打開的新標簽頁
var opener=open('http://localhost:3000');
2.從當前文檔中向目標文檔發送消息
targetDocument.postMessage('a string content','http://www.example.com');
//這里的url就明確指定了,接收消息的文檔必須來自該url
3.目標文檔接到消息
目標文檔中要注冊事件監聽
window.addEventListener('message', function(event) {
// 這里可以得到消息的來源,內容等信息
}, false)
~~~
* * * * *
### 實例
~~~
在有一個 url 為 http://localhost:3000 的網頁里,嵌了一個 url為 http://localhost:3001 的iframe
<iframe src="http://localhost:3001/frame/" id="frame"></iframe>
主頁面的 js
<script type="text/javascript">
var opener;
/* 向打開的新標簽頁發消息 */
document.getElementById('btn').onclick = function() { // 取得目標引用
opener = window.open('/open/');
};
document.getElementById('send').onclick = function() { // 發送消息
opener.postMessage('Hi I am from Main Page !', '*');
}
/* 向iframe里發送消息 */
var frame=document.getElementById('frame').contentWindow;
frame.postMessage(3333,'http://localhost:3001');
</script>
iframe或新標簽頁里的腳本
<script type="text/javascript">
/* 這里會接收到信息 */
window.addEventListener('message', function(event) {
console.log(event);
}, false);
</script>
~~~
* * * * *
### 參數解釋
~~~
postMessage 方法的參數:
第一個,所要發送的消息,可以為字符串,對象等;
第二個,
a. '*' (表示可以被任何文檔接收);
b. 指定接收方的url,必須有匹配的文檔,否則報錯;
message事件的事件對象event 的主要參數:
data 發送過來的數據
origin 調用postMessage方法的文檔的 origin
source 對發送消息的窗口的對象的引用,可以使用它再次回發內容,雙向交互
~~~
* * * * *
>[success] PS:本例使用node的express搭建本地服務做測試,必須是在http協議下才會生效,本地文件不生效