該方法是HTML5用于跨域消息傳輸?shù)腁PI
發(fā)送窗口
window.postMessage()方法被調(diào)用時植兰,會在所有頁面腳本執(zhí)行完畢之后(e.g., 在該方法之后設(shè)置的事件、之前設(shè)置的timeout 事件,etc.)向目標(biāo)窗口派發(fā)一個 MessageEvent消息稳诚。 該MessageEvent消息有四個屬性需要注意:
message 屬性表示該message 的類型;
data 屬性為 window.postMessage的第一個參數(shù);
origin 屬性表示調(diào)用window.postMessage()方法時調(diào)用頁面的當(dāng)前狀態(tài);
source 屬性記錄調(diào)用window.postMessage()方法的窗口信息称勋。
語法
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow:表示發(fā)送數(shù)據(jù)的窗口的window的引用,包括iframe的contentWindow屬性和通過window.open打開的新窗口涯竟。
message表示要發(fā)送的數(shù)據(jù)赡鲜,包擴(kuò)字符串和對象(ie9以下不支持,可以利用字符串和json互換)昆禽。
origin表示接收窗口的域蝗蛙。
接收窗口
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
// For Chrome, the origin property is in the event.originalEvent
// object.
var origin = event.origin || event.originalEvent.origin;
if (origin !== "http://example.org:8080")
return;
// ...
}
回調(diào)函數(shù)接受一個事件對象event, event包含屬性
data:接受的數(shù)據(jù)
origin:發(fā)送窗口的域
source:發(fā)送端的DOMWindow對象