一、發送消息
otherWindow.postMessage(message, targetOrigin, [transfer]);
-
otherWindow:其他窗口的一個引用,如iframe的contentWindow屬性、Window.open、Window.opener、Window.parent、Window.frames +索引值。
-
message:將要發送到其他 window的數據。
-
targetOrigin:指定目標窗口的來源,必須與消息發送目標相一致,可以是字符串“*”或URI。 *表示任何目標窗口都可接收,爲安全起見,請一定要明確提定接收方的URI。
-
transfer :可選。
二、接收消息
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event){
if (event.origin !== "http://www.42du.cn")
return;
}
event對象有三個屬性,分別是origin,data和source
-
event.origin表示postMessage的發送來源,包括協議,域名和端口;
-
event.data表示接收到的消息;
-
event.source表示發送消息的窗口對象的引用;
我們可以用這個引用來建立兩個不同來源的窗口之間的雙向通信。
發送程序:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>發送程序</title>
</head>
<body>
<div>
<input id="val" type="text" value="易安_小葵坤" />
<button id="sendbtn" >發送消息</button>
</div>
<iframe id="receiver" src="http://res.42du.cn/static/html/receiver.html" width="500" height="500"><p>你的瀏覽器不支持IFrame。</p></iframe>
<script>
window.onload = function() {
var receiver = document.getElementById("receiver").contentWindow;
var sendbtn = document.getElementById("sendbtn");
sendbtn.addEventListener("click", function (e) {
e.preventDefault();
var val = document.getElementById("val").value;
receiver.postMessage("Hello "+val+"!", "http://res.42du.cn");
});
}
</script>
</body>
</html>
接收程序:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>接收程序</title>
</head>
<body>
<div id="message">Hello World!</div>
<script>
window.onload = function() {
var receiveMsg = document.getElementById("message");
window.addEventListener("message", function (e) {
if (e.origin !== "http://www.42du.cn") {
return;
}
receiveMsg.innerHTML = "從"+ e.origin +"收到消息: " + e.data;
});
}
</script>
</body>
</html>