2

使用window.postMessage实现跨域通信

 2 years ago
source link: https://blogread.cn/it/article/7286?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用window.postMessage实现跨域通信

浏览:1550次  出处信息

JavaScript由于同源策略的限制,跨域通信一直是棘手的问题。当然解决方案也有很多:

  • document.domain+iframe的设置,应用于主域相同而子域不同;

  • 利用iframe和location.hash,数据直接暴露在了url中,数据容量和类型都有限

  • Flash LocalConnection, 对象可在一个 SWF 文件中或多个 SWF 文件间进行通信, 只要在同一客户端就行,跨应用程序, 可以跨域。

  • window.name 保存数据以及跨域 iframe 静态代理动态传输方案,充分的运用了window.name因为页面的url改变而name不改变的特性。

各种方案网上都有很多实例代码,大家可以自己搜索一下。
html5中最炫酷的API之一:就是  跨文档消息传输Cross Document Messaging。高级浏览器Internet Explorer 8+, chrome,Firefox , Opera  和 Safari 都将支持这个功能。这个功能实现也非常简单主要包括接受信息的”message”事件和发送消息的”postMessage”方法。

发送消息的”postMessage”方法

向外界窗口发送消息:

  1. otherWindow.postMessage(message, targetOrigin);

otherWindow: 指目标窗口,也就是给哪个window发消息,是 window.frames 属性的成员或者由 window.open 方法创建的窗口

参数说明:

  • message:  是要发送的消息,类型为 String、Object (IE8、9 不支持)

  • targetOrigin:  是限定消息接收范围,不限制请使用 ‘*’

接受信息的”message”事件

  1. var onmessage =function(event){

  2. var data = event.data;

  3. var origin = event.origin;

  4. //do someing

  5. if(typeof window.addEventListener !='undefined'){

  6.    window.addEventListener('message', onmessage,false);

  7. }elseif(typeof window.attachEvent !='undefined'){

  8. //for ie

  9.    window.attachEvent('onmessage', onmessage);

回调函数第一个参数接收 Event 对象,有三个常用属性:

  • data:  消息

  • origin:  消息来源地址

  • source:  源 DOMWindow 对象

看一个简单的来自网上的demo: http://www.css88.com/demo/postmessage/

建议继续学习:

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK