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进行通信
- <html>
- <head>
- <title>Cross Frame Messaging with postMessage</title>
- </head>
- <body>
- <h3>Parent Document (examples.proiedev.com)</h3>
- Post message to remote document (.ie-examples.com):
- <input id="postDataInput" size="25" type="text">
- <input onclick="postToRemote();" type="submit" value="Post Message"><br><br>
- <iframe id="remoteFrame"
- src="http://.ie-examples.com/03/xcomm/xdm/remote"
- width="400px" height="200px" class="highlightBorder"
- frameborder="no"></iframe>
- <script type="text/javascript">
- // Post contents of an input box to a remote page
- function postToRemote() {
- // Grab the input value from the box (explicitly type as a string to
- // avoid pulling in a VT_NULL (IE Bug) and quit if empty
- var postData = String(document.getElementById("postDataInput"). value);
- if (postData == "") return;
- // Use postMessage to send the string message over to the remote page
- var remote = document.getElementById("remoteFrame");
- remote.contentWindow.postMessage(postData, "http://.ie-examples.com");
- }
- </script>
- </body>
- </html>
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-35014-1.html