跨页面的Websocket JavaScript [英] Websocket across pages JavaScript

查看:196
本文介绍了跨页面的Websocket JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JS中实现了一个基本的websockets客户端:

I have implemented a basic websockets client in JS:

function connectToNotifServer(){

var conn = new WebSocket('ws://localhost:8080');

conn.onopen = function(e) {
    alert("Connection established!");
    conn.send(JSON.stringify({user_id: sessionStorage.getItem("user_id")}));
};

conn.onmessage = function(e) {
    alert(e.data);
};

conn.onclose = function(e) {
    alert("Connection closed!");
};
return conn;
}

但我想在页面上使用websocket连接。但是,如果我只是在加载时调用此方法,那么我担心每次重新加载页面时都会建立新连接,这是一个问题吗?无论如何,有没有连接一次并在不同页面和页面重新加载时使用它?

But I want to use the websocket connection on a page. However, if I simply call this method on load, then I am concerned a new connection will be made each time the page is reloaded, is this a problem?. Is there anyway, to make a connection once and use that throughout different pages and page reloads?

谢谢

推荐答案

您可以通过从共享后台Web工作者打开WebSocket连接来完成此操作。

You can do this by opening the WebSocket connection from a shared background Web worker.

WebSocket连接至少保持打开状态一个选项卡对于给定来源(共享Web工作者)仍处于活动状态。

The WebSocket connection will stay open when at least one tab is still active to the given origin (of the shared Web worker).

我知道Chrome和IE11支持从专用Web工作者打开WebSocket连接。 Firefox目前没有。我不知道哪些浏览器支持来自共享 Web worker的WebSocket连接(这是您需要的)。

I know that Chrome and IE11 support opening WebSocket connections from dedicated Web workers. Firefox does not currently. I don't know which browsers support WebSocket connection from shared Web workers (which is what you'd need).

这篇关于跨页面的Websocket JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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