zoukankan      html  css  js  c++  java
  • 2个浏览器窗口间通信

    1.localStorage

    一个窗口更新localStorage,另一个窗口监听window对象的“storage”事件,来实现通信

    注:两个页面要同源

    //本窗口的设置代码
    localStorage.setItem('aaa', (Math.random() * 10).toString())
    //其他窗口监听storage事件
    window.addEventListener("storage", function(e){
       console.log(e)
       console.log(e.newValue)  
    })

    2. WebSocket

    所有的WebSocket都监听同一个服务器地址,利用send发送消息,利用onmessage获取消息的变化,不仅能多窗口,还能跨浏览器,兼容性最佳,只是需要消耗点服务器资源。

    var ws = new WebSocket("ws://localhost:3000/")
    ws.onopen = function(event){
      //或者把此方法注册到其他事件中,即可与其他服务器通信
      ws.send({now: Date.now()});  //通过服务器中转消息    
    };
    ws.onmessage = function(event) {
      //消费消息
      console.log(event.data);    
    }

    3. postMessage

    借助iframe 或 window.open

    回顾一下API

    otherWindow.postMessage(message, targetOrigin, [transfer]);

    1) otherWindow

    其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames.

    2) message

    将要发送到其他window的数据。它将会被结构化克隆算法序列化。这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化。

    3) targetOrigin

    通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串“”(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或者端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如:当用postMessage传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的origin属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个确切值的targetOrigin,而不是,不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。

    4) transfer可选

    是一串和message同时传递的Transferable对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

    /*
     * A窗口的域名是<http://example.com:8080>,以下是A窗口的script标签下的代码:
     *
     */
    
    var popup = window.open(...popup details...);
    
    //如果弹出框没有被阻止且加载完成
    
    //这行语句没有发送消息出去,即使假设当前页面没有改变location(因为targetOrigin设置不对)
    popup.postMessage("The user is 'bob' and the password is 'secret'", "https://secure.example.net");
    
    //假设当前页面没有改变location,这条语句会成功添加message到发送队列中去(targetOrigin设置对了)
    popup.postMessage("hello there!", "http://example.org");
    
    function receiveMessage(event) {
        //我们能相信信息的发送者吗?(也许这个发送者和我们最初打开的不是同一个页面)
      if(event.origin !== "http://example.org") return;
    
    //event.source 是我们通过window.open打开的弹出页面 popup
    //event.data 是 popup发送给当前页面的消息 "hi there yourself! the secret response is: rheeeeeet!"
    }
    
    window.addEventListener("message", receiceMessage, false);
    /*
     * 弹出页 popup 域名是<http://example.org>,以下是script标签中的代码:
     *
     */
    function receiveMessage(event) {
       //我们能信任信息来源吗?
      if (event.origin !== "http://example.com:8080") return;
    
       //event.source 就当前弹出页的来源页面
       //event.data 是 "hello there!"
    
       //假设你已经验证了所收到信息的origin(任何时候你都应该这样做),
    //一个很方便的方式就是把event.source作为回信的对象,并且把event.origin作为targetOrigin
      event.source.postMessage("hi there yourself! the secert response " + "is: rheeeet!", event.origin); } window.addEventListener("message", receiveMessage, false);

    4. cookie + setInterval【差】

    在页面A设置一个使用 setInterval定时器不断刷新,检查Cookies的值是否发生变化,如果变化就进行刷新的操作。

    由于Cookies是在同域可读的,所以在页面B审核的时候改变Cookies的值,页面A自然是可以拿到的。

    这样做确实可以实现想要的功能,但是这样的方法相当浪费资源。虽然在这个性能过盛的时代,浪费不浪费感觉不出来,但是这种方案,确实不够优雅。

    5. SharedWorker

    HTML5中的Web Worker 可以分为2种不同的线程类型,一个是专用线程 Dedicated Worker,一个是共享线程 Shared Worker。

    1) Dedicated Worker 直接使用 new Worker() 即可创建,这种webworker是当前页面专有的。

    2) SharedWorker 可以被多个window、标签页、iframe共同使用,但必须保证这些标签页都是同源的(相同的协议、主机和端口号)

    6.直接引用

    其实就是直接获取对方DOM,适用于2个页面在同一域;可以传递对象数据(对象数据使用 instanceof 做类型判断时有坑);参考window.open;

    例:

    //父页面获取iframe
    document.getElementById("iframe的id").contentWindow.document
    
    //子iframe获取父页面
    window.parent.document

    7. window.name

    浏览器窗口有window.name属性。这个属性的最大特点是,无论是否同源,只要在同一窗口里,前一个网页设置了这个属性,后一个网页可以读取它。

    父窗口先打开一个子窗口,载入一个不同源的网页,该网页将信息写入window.name属性

    window.name = data

    接着,子窗口跳回一个与主窗口同域的网址

    window.location.href = "http://parent.url.com/xxx.html";

    然后,主窗口就可以读取子窗口的window.name了

    var data = document.getElementById("iframe的id").contentWindow.name;

    这种方法的优点是,window.name容量最大,可以放置非常长的字符串;缺点是必须监听子窗口window.name属性的变化,影响网页性能。

  • 相关阅读:
    Split Temporary Variable
    Introduce Explaining Variable
    Replace Temp with Query
    Extract Method
    自测代码的价值
    代码的坏味道
    Divergent Change & Shotgun Surgery
    Large Class
    Long Method
    Duplicated Code
  • 原文地址:https://www.cnblogs.com/starrk-01/p/9945608.html
Copyright © 2011-2022 走看看