JavaScript使用HTML5的window.postMessage实现跨域通信例子

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

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

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

  3.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”方法

  

  向外界窗口发送消息:

  

复制代码 代码如下:
otherWindow.postMessage(message, targetOrigin);

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

  参数说明:

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

  2.targetOrigin: 是限定消息接收范围,不限制请使用 ‘*'

  接受信息的”message”事件

  

  

复制代码 代码如下:

  var onmessage = function (event) {

  var data = event.data;

  var origin = event.origin;

  //do someing

  };

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

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

  } else if (typeof window.attachEvent != 'undefined') {

  //for ie

  window.attachEvent('onmessage', onmessage);

  }

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

  1.data: 消息

  2.origin: 消息来源地址

  3.source: 源 DOMWindow 对象

  当然postmessage也有一些不足的地方:

  1.ie8,ie9下传递的数据类型值支持字符串类型,不过可以使用用 JSON对象和字符串之间的相互转换 来解决这个问题;

  2.ie6,ie7需要写兼容方案,个人认为window.name比较靠谱;