Home > Web Front-end > H5 Tutorial > body text

html5 跨文档消息传输示例探讨_html5教程技巧

WBOY
Release: 2016-05-16 15:49:49
Original
1302 people have browsed it

对窗口对象的message事件进行监听

复制代码
代码如下:

window.addEventListener("message", function(event) {
// 处理程序代码
}, false);

使用window对象的postMessage()方法向其他窗口发送消息,该方法的定义如下:

复制代码
代码如下:

otherwindow.postMessage(message, targetOrigin);

该方法使用两个参数:第一个参数为所发送的消息文本,但也可以是任何JavaScript对象(通过JSON转换对象为文本);第二个参数为接收消息的对象窗口的URL地址,可以在URL地址字符串中使用通配符“*”指定全部地址,不过建议使用准确的URL地址。otherwindow为要发送窗口对象的引用,可以通过window.open()方法返回该对象,或通过对window.frames数组指定序号(index)或名字的方式来返回单个frame所属性的窗口对象。
示例

复制代码
代码如下:





跨文档消息传输示例主文档





跨域通信示例







子页面中的代码如下:

复制代码
代码如下:









这是iframe中的内容。






•通过对window对象的message事件进行监听,可以接收消息。
•通过访问message事件的origin属性,可以获取消息的发送源(本例中主页面的发送源为“http://Lulingniu”,子页面的发送源为“http://www.blue-butterfly.net”)。注意:发送源与网站的URL地址不是一个概念,发送源只包括域名与端口号,为了不接收其他源恶意发送过来的消息,最好对发送源做检查。
•通过访问message事件的data属性,可以取得消息内容(可以是任何JavaScript对象,使用JSON)。
•使用postMessage()方法发送消息。
•通过访问message事件的source属性,可以获取消息发送源的窗口的代理对象。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!