postmessage用法_postmessage_postmessage是什么

电脑杂谈  发布时间:2017-02-28 15:12:45  来源:网络整理

3.5.2 用postMessage()进行跨框架消息发送

如果开发人员所构建的网页中包含多个起点(这种网页通常称为"mashup"),(网页与<iframe>之间的)跨框架通信通常会成为一个痛点。关于<iframe>对象及其宿主程序能够做些什么,以及它们如何进行通信,IE和其他浏览器都采取了一些严格的安全性措施。尽管这种隔离是有必要的,但也隔断了它们之间的通信。为了克服这一限制,开发人员将document.location.hash看作共有的数据存储区。

HTML5规范中创建了postMessage()方法和onmessage事件,作为父对象与其子<iframe>对象之间的通信方式。它们可以使用这一方法发送和接收数据,并强制宿主浏览器对请求实施基于起点的限制。

Internet Explorer 8为所有文档模式实现了这一功能-- postMessage()方法和onmessage事件。

对象

postMessage(msg [, targetOrigin])方法--发送在字符串msg中指定的消息。通过targetOrigin进一步设置限制,它限制了允许接收该消息的内容起点。postmessage

事件

onmessage事件--当目标窗口对象接收一条使用postMessage()方法发送的消息时,会触发此事件。消息本身将存储在事件对象的一个属性中。

属性

Origin属性--返回发送该消息的文档起点。

Data属性--返回由origin文档发送的消息。

Type属性--事件的类型,在本例中为message。

代码清单3-24中的代码示例显示了托管<iframe>的父文档,在IE8中,这两个文档可以用postMessage相互发送消息。这个页面包含<input>文本框和提交按钮;提交按钮的onlick事件通过<iframe>的contentWindow实例上的postMessage,将<input>文本框的内容发送到iframe。

代码清单3-24 此代码给出一个托管框架对象的父文档,并用postMessage进行通信

  1. <html> 
  2. <head> 
  3. <title>Cross Frame Messaging with postMessage</title> 
  4. </head> 
  5. <body> 
  6. <h3>Parent Document (examples.proiedev.com)</h3> 
  7. Post message to remote document (.ie-examples.com):&nbsp;&nbsp;  
  8. <input id="postDataInput" size="25" type="text">&nbsp;&nbsp;  
  9. <input onclick="postToRemote();" type="submit" value="Post Message"><br><br> 
  10. <iframe id="remoteFrame" 
  11. src="http://.ie-examples.com/03/xcomm/xdm/remote" 
  12. width="400px" height="200px" class="highlightBorder" 
  13. frameborder="no"></iframe> 
  14. <script type="text/javascript"> 
  15. // Post contents of an input box to a remote page  
  16. function postToRemote() {  
  17. // Grab the input value from the box (explicitly type as a string to  
  18. // avoid pulling in a VT_NULL (IE Bug) and quit if empty  
  19. var postData = String(document.getElementById("postDataInput"). value);  
  20. if (postData == "") return;  
  21. // Use postMessage to send the string message over to the remote page  
  22. var remote = document.getElementById("remoteFrame");  
  23. remote.contentWindow.postMessage(postData, "http://.ie-examples.com");  
  24. }  
  25. </script> 
  26. </body> 
  27. </html> 


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-35014-1.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...