在HTML5中新增了postMessage方法,postMessage可以实现跨文档消息传输(Cross Document Messaging),Internet Explorer 8, Firefox 3, Opera 9, Chrome 3和 Safari 4都支持postMessage。
可以通过绑定window的message事件来监听发送跨文档消息传输内容。示例代码如下: eg.) parent page
<!DOCTYPE HTML> <html> <head> <title>Communication</title> <script> var messageChange = function(e) { var data = e.data; var origin = e.origin; if (origin !== "http://www.") return; document.getElementById('display').innerHTML = data; }; if (typeof window.addEventListener != 'undefined') { window.addEventListener('message', messageChange, false); } else if (typeof window.attachEvent != 'undefined') { window.attachEvent('onmessage', messageChange); } </script> </head> <body> <div id="display">Say something!</div> <iframe scrolling="no" frameborder="0" width="0" height="0" src="http://www./html5/postMessage/sub.html"></iframe> </body> </html> eg.) sob page
<!DOCTYPE HTML> <html> <head> <title>Communication</title> <script> setInterval(function(){ window.parent.postMessage("hello world!", "http://www."); },1000); </script> </head> <body></body> </html>
DEMO见附件, 更多HTML5相关demo地址:http:/// |
|