zoukankan      html  css  js  c++  java
  • HTML5之window.postMessage API

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

    • document.domain+iframe的设置,应用于主域相同而子域不同;
    • 利用iframelocation.hash,数据直接暴露在了url中,数据容量和类型都有限
    • Flash LocalConnection, 对象可在一个 SWF 文件中或多个 SWF 文件间进行通信, 只要在同一客户端就行,跨应用程序, 可以跨域。
    • window.name 保存数据以及跨域 iframe 静态代理动态传输方案,充分的运用了window.name因为页面的url改变而name不改变的特性。

    window postMessage允许两个窗口 帧之间跨域发送数据消息。从本质上讲,window postMessage是一个跨域的无服务器垫片的Ajax。让我们一起来看看window postMess

      跨文档消息传输Cross Document Messaging 。高级浏览器Internet Explorer 8+, chromeFirefox , Opera  和 Safari 都将支持这个功能。这个功能实现也非常简单主要包括接受信息的”message”事件和发送消息的”postMessage”方法。

    发送消息的”postMessage”方法

    向外界窗口发送消息:

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

    参数说明:

    • message:   是要发送的消息,类型为 String、Object (IE8、9 不支持)
    • targetOrigin:   是限定消息接收范围,不限制请使用 ‘*’

    接受信息的”message”事件

    var onmessage = function (event) {
      var data = event.data;
      var origin = event.origin;
      //TODO
    };
    if (window.addEventListener) {
      window.addEventListener('message', onmessage, false);
    } else if (window.attachEvent) {
      //For IE
      window.attachEvent('onmessage', onmessage);
    }

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

    • data:   消息
    • origin:   消息来源地址
    • source:   源 DOMWindow 对象
  • 相关阅读:
    ajax专题
    luogu P1346 电车 最短路
    luogu P1462 通往奥格瑞玛的道路 最短路
    luogu P1328 生活大爆炸版石头剪刀布
    luogu P1315 联合权值 枚举
    luogu P1156 垃圾陷阱 背包问题
    luogu P1217 回文质数 枚举
    luogu P3650 滑雪课程设计 枚举
    luogu1209 修理牛棚 贪心
    luogu P1223 排队接水 贪心
  • 原文地址:https://www.cnblogs.com/qiuleo/p/4582705.html
Copyright © 2011-2022 走看看