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.结果