两个浏览器窗口间通信总结

时间:2020-07-18 00:49:09   收藏:0   阅读:61

1、localStorage

一个窗口更新localStorage,另一个窗口监听window对象的”storage”事件,来实现通信。
注:两个页面要同源(URL的协议、域名和端口相同)

// 本窗口的设值代码
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]);
/*
 * 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: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);


/*
 * 弹出页 popup 域名是<http://example.org>,以下是script标签中的代码:
 */

//当A页面postMessage被调用后,这个function被addEventListenner调用
function receiveMessage(event)
{
  // 我们能信任信息来源吗?
  if (event.origin !== "http://example.com:8080")
    return;

  // event.source 就当前弹出页的来源页面
  // event.data 是 "hello there!"

  // 假设你已经验证了所受到信息的origin (任何时候你都应该这样做), 一个很方便的方式就是把enent.source
  // 作为回信的对象,并且把event.origin作为targetOrigin
  event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);

  

新片场https://www.wode007.com/sites/73286.html 傲视网https://www.wode007.com/sites/73285.html

4、cookie + setInterval【差】

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

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

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

 

5、SharedWorker

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

 

6、直接引用

适用于两个页面在同一域;可以传递对象数据(对象数据使用 instanceof 做类型判断时有坑);参考 window.open;

原文:https://www.cnblogs.com/ypppt/p/13334084.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!