接收監(jiān)聽(tīng)消息:
window.addEventListener("message", function() {...}, false);
發(fā)送窗口:
otherWindow.postMessage(message, targetOrigin);
頁(yè)面A代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跨域通信示例</title>
<script type="text/javascript">
// (1) 監(jiān)聽(tīng)message事件
window.addEventListener("message", function (ev) {
// (2) 忽略指定URL地址之外的頁(yè)面?zhèn)鬟^(guò)來(lái)的消息
if (ev.origin != "http://127.0.0.1:5500") {
return;
}
// (3) 顯示消息
document.getElementById("content").innerHTML = ("從" + ev.origin + "那里傳過(guò)來(lái)的消息:\n\"" + ev.data + "\"");
}, false);
function hello() {
var iframe = window.frames[0];
// (4) 傳遞消息
iframe.postMessage("你好", "http://127.0.0.1:5500/html5/test11-2.html");
}
</script>
</head>
<body>
<div>頁(yè)面A</div>
<h1>跨域通信示例</h1>
<div id="content"></div>
<iframe width="400" src="http://127.0.0.1:5500/html5/test11-2.html" onload="hello()">
</iframe>
</body>
</html>
頁(yè)面B代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>頁(yè)面B</div>
<div id="content"></div>
<script>
window.addEventListener("message", function(ev) {
if (ev.origin != "http://127.0.0.1:8080") {
return;
}
document.getElementById("content").innerHTML = "從"+ev.origin+"那里傳來(lái)的消息<br>"+ev.data;
ev.source.postMessage("你好哭尝,這里是"+this.location, ev.origin);
}, false);
</script>
</body>
</html>
效果圖如下: