在HTML5中新增了postMessage方法,postMessage可以实现跨文档消息传输(Cross Document Messaging),Internet Explorer 8, Firefox 3, Opera 9, Chrome 3和 Safari 4都支持postMessage。
该方法可以通过绑定window的message事件来监听发送跨文档消息传输内容。
父页面:
var OnMessage = function (e) {
alert(e.data);
}
if (window.addEventListener) { // all browsers except IE before version 9
window.addEventListener("message", OnMessage, false);
} else {
if (window.attachEvent) { // IE before version 9
window.attachEvent("onmessage", OnMessage);
}
}
子页面:
<script type="text/javascript">
window.parent.postMessage("hello","*");
</script>
父页面:
var OnMessage = function (e) {
alert(e.data);
}
if (window.addEventListener) { // all browsers except IE before version 9
window.addEventListener("message", OnMessage, false);
} else {
if (window.attachEvent) { // IE before version 9
window.attachEvent("onmessage", OnMessage);
}
}
子页面:
<script type="text/javascript">
window.parent.postMessage("hello","*");
</script>