父頁面:
<html>
<body>
<h2>page A</h2>
<h1 class="header">page A</h1>
<div class="mb20">
<button style="font-size:20px;" onclick="send()">post message</button>
</div>
<!-- 跨域的情況 -->
<iframe src="http://localhost:8880/#/login" name="frmName" style="display: none; "></iframe>
<script>
//發(fā)送消息給子頁面
function send() {
var data = {};
//我用這個(gè)來作為某類消息
data.msgType = "login";
data.a1="hello";
//iframe的src需要和下面第二個(gè)參數(shù)的域相同,不然會(huì)有錯(cuò)誤信息在控制臺(tái)
window.frames['frmName'].postMessage(data, 'http://localhost:8880/#/login'); // 觸發(fā)跨域子頁面的messag事件
}
var varWindow = window;
//接收子頁面返回的消息(注意:這個(gè)listen也可以接受其它頁面postmessage過來的消息)
window.addEventListener('message', function(messageEvent) {
var data = messageEvent.data;
console.info('message from child:', data);
varWindow.open('http://localhost:8880/#/dashboard');
}, false);
</script>
</body>
</html>
子頁面:只要有addEventListener即可
window.addEventListener('message', function(ev) {
var data = ev.data;
console.info('message from parent:', data);
//一般這類有特殊用途的页眯,都加個(gè)msgType,這樣可以過濾掉其它postmessage蔗彤。目前還不得而知是否有聰明點(diǎn)的辦法
if(data.msgType!=null && data.msgType === 'login'){
//登錄操作,保存登錄信息到local storage柳爽,然后父頁面window.open到Index頁面本姥,即可完成跨域登錄
parent.postMessage("OK", 'http://localhost:8080/');
}
}, false);