标签:window.postMessage

共 2 篇相关文章

IT 累计浏览 2,547

使用window.postMessage实现跨域通信

JavaScript 受同源策略限制,跨域通信一直比较棘手。传统方案各有局限:document.domain + iframe 仅适用于主域相同子域不同的场景;iframe 配合 location.hash 会把数据暴露在 URL 中,容量和类型都受限;Flash LocalConnection 依赖 SWF;window.name 则利用页面 URL 改变而 name 不变的特性。HTML5 提供的跨文档消息传输(Cross Document Messaging)是更简洁的选择,IE8+、Chrome、Firefox、Opera、Safari 均已支持。

该 API 主要由发送消息的 postMessage 方法和接收消息的 message 事件组成。发送时调用 otherWindow.postMessage(message, targetOrigin),otherWindow 是目标窗口(window.frames 成员或 window.open 创建的窗口),message 可为 String 或 Object,targetOrigin 用来限定消息接收范围,不限制可用 '*'。接收端通过 window.addEventListener('message', onmessage)(IE 用 attachEvent)监听,回调的 Event 对象中 data 为消息内容,origin 为消息来源地址,source 为源 DOMWindow 对象。

不过 postMessage 也有不足:IE8、IE9 下只支持传递字符串类型,可借助 JSON 对象与字符串的相互转换解决;IE6、IE7 需另写兼容方案,其中 window.name 较为靠谱。

IT 累计浏览 4,424

使用window.postMessage实现跨域通信

由于同源策略的限制,JavaScript 跨域通信一直比较棘手,常见方案包括 document.domain+iframe(适用于主域相同子域不同)、iframe 配合 location.hash(数据暴露在 url 中,容量和类型有限)、Flash LocalConnection,以及利用 window.name 页面 url 改变而 name 不变特性的跨域 iframe 代理方案。HTML5 提供的跨文档消息传输 Cross Document Messaging 则更简洁,IE8+、Chrome、Firefox、Opera、Safari 均支持,核心就是 postMessage 方法和 message 事件。

发送时用 otherWindow.postMessage(message, targetOrigin),otherWindow 指目标窗口(window.frames 成员或 window.open 创建的窗口),message 可为 String 或 Object(IE8、9 不支持 Object),targetOrigin 限定接收范围,不限制用 '*'。接收端监听 message 事件,回调的 Event 对象常用 data(消息)、origin(消息来源地址)、source(源 DOMWindow)三个属性,注意用 addEventListener 与 attachEvent 做兼容。

不过 postMessage 也有不足:IE8、9 下只支持字符串类型,可通过 JSON 对象和字符串互转解决;IE6、7 需另写兼容方案,作者认为 window.name 方案比较靠谱。