How to maintain a WebSockets connection between pages?

The global scope you mentioned is always related to the JavaScript Context, and a Context is created for each windows (and destroyed when the document is unloaded from the memory). Therefore, your effort are useless: you can’t keep a connection opened if the user change page.
Of course you can have your webapp as “single page” application, where all the data are loaded using XMLHttpRequest / ajax / WebSocket. So, leaving the page means leaving / shutdown the application, and makes sense close the socket.

Another old approach could be put your pages in a frame, where the user navigate only in the frame (even if it takes the whole size of the window). In that way, you can create your WebSocket in the top most window, that is never changed (that also means the URL showed in the location bar will be always the same).

Said that, I agreed with @dystroy: your application should be always able to handle this scenario – the user could have some network problem and lost the connection for a moment, even if it doesn’t leave the page.

Leave a Comment