1. 程式人生 > >iframe 利用postMessage 跨域通訊

iframe 利用postMessage 跨域通訊

1.子頁面:http://localhost:7080/b.jsp

<button onclick="send()">send</button>

<script>
window.addEventListener('message', function(ev) {
    var data = ev.data;
    console.info('message from parent:', data);
}, false);

function send() {
    parent.postMessage("hello", 'http://localhost:8080/'); // 若父頁面的域名和指定的不一致,則postMessage失敗
}
</script>

2.父頁面:http://localhost:8080/a.jsp

<button style="font-size:20px;" onclick="send()">post message</button>
<iframe src="http://localhost:7080/b.jsp"></iframe>

<script>
function send() {
    var data = {name:"111",age:"222"};
	window.frames[0].postMessage(data, 'http://localhost:7080'); // 觸發跨域子頁面的messag事件
}

window.addEventListener('message', function(messageEvent) {
    var data = messageEvent.data; 
    console.info('message from child:', data);
}, false);
</script>

3.結果