跨浏览器选项卡共享 websocket? [英] Sharing websocket across browser tabs?

查看:44
本文介绍了跨浏览器选项卡共享 websocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望每个浏览器都有一个套接字,而不是浏览器中的每个选项卡一个.我们怎样才能实现它?我读到了很有前途的共享网络工作者.对此的参考也表示赞赏.不幸的是,就我所知,mozilla 或 Internet Explorer 尚未实现共享的 Web Worker.那么在这种情况下该怎么办?我们正在服务器端开发 node.js.

We want to have one socket per browser rather than one per tab in a browser. How can we achieve it? I read about shared web workers which was promising. A reference for that too is appreciated. Unfortunately shared web workers are not yet implemented by mozilla or internet explorer to the best of my knowledge. So what to do in this case ? We are working on node.js on server side.

推荐答案

看到这个问题,我终于实现了共享套接字,并在几天前添加到我的库中.它似乎适用于大多数浏览器,甚至包括 IE6,但 Opera 除外.对于 Opera,您可以使用定期检查而不是卸载事件.

After seeing this question, I've finally implemented sharing socket and added to my library a few days ago. It seems to work in most of browsers including even in IE6, but except Opera. For Opera, you may use regular checking instead of unload event.

https://github.com/flowersinthesand/portal/issues/21<检查相关问题/a>

Check releated issue at https://github.com/flowersinthesand/portal/issues/21

  1. 设置 cookie 以通知存在共享套接字.
  2. 当套接字关闭时,删除该 cookie 以通知没有共享套接字.

见,https://github.com/Flowersinthesand/portal/blob/7c2ce4bb61d05d80580e6cde6c94a78238a67345/jquery.socket.js#L629-650

  1. 使用存储事件和 localStorage - localStorage 在设置和删除值时触发存储事件.
  1. Using the storage event and localStorage - The localStorage fires the storage event when a value is set and removed.
  1. 检查是否支持 StorageEvent 和 localStorage.
  2. 添加按键过滤事件的存储事件处理程序.我用socket的url作为key
  3. 添加删除存储属性的socket关闭事件
  4. 要发出信号,请使用前一个键将数据设置为存储

分享:https://github.com/Flowersinthesand/portal/blob/7c2ce4bb61d05d80580e6cde6c94a78238a67345/jquery.socket.js#L531-568

使用共享:https://github.com/flowersinthesand/portal/blob/7c2ce4bb61d05d80580e6cde6c94a78238a67345/jquery.socket.js#L851-893

  1. 使用 window.open 方法 - 如果我们知道共享窗口的名称,我们可以获取该窗口的引用并访问其属性.
  1. Using the window.open method - If we know a shared window's name, we can get that window's reference and access its property.
  1. 每个浏览器都支持 window.open 方法,但某些浏览器(如 Chrome)禁止访问返回窗口的属性.
  2. 获取或创建名称属性为键的 iframe.我用的是socket的url,但是注意IE不允许在iframe标签的name属性中使用非单词字符.
  3. Iframe 的 contentWindow 是一个共享窗口引用.设置回调变量以存储每个窗口的侦听器.
  4. 要发出信号,只需使用数据调用回调即可.请注意,IE 8 及更低版本只允许将字符串传递给其他窗口的函数,并且共享窗口可能会被销毁.

分享:https://github.com/Flowersinthesand/portal/blob/7c2ce4bb61d05d80580e6cde6c94a78238a67345/jquery.socket.js#L571-605

使用共享:https://github.com/flowersinthesand/portal/blob/7c2ce4bb61d05d80580e6cde6c94a78238a67345/jquery.socket.js#L894-929

  1. 在上面的实现中,信令是广播,所以数据应该指示目标.我使用了目标属性,p 代表父级,c 代表子级.
  2. 我使用了额外的变量来共享套接字:opened - 共享套接字是否打开,children - 共享者列表.代码和注释将帮助您了解详细信息.

希望我的回答对您有所帮助.

I hope my answer was helpful.

这篇关于跨浏览器选项卡共享 websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆