You could try creating your WebSocket connection in a Shared WebWorker which allows multiple pages from the same domain to share an execution context. However, it's unclear whether Shared Workers persist across a page reload or replace: Do Shared Web Workers persist across a single page reload, link navigation
Also, Shared WebWorkers have limited browser support (webkit and Opera) currently.
Update:
Since a single shared web worker can serve multiple pages, the implementation is slightly more complicated that normal web workers.
Here is a shared web worker example that uses WebSockets and can share between
First the HTML:
<!DOCTYPE html>
<html>
<body>
<script>
var worker = new SharedWorker("shared.js");
worker.port.addEventListener("message", function(e) {
console.log("Got message: " + e.data);
}, false);
worker.port.start();
worker.port.postMessage("start");
</script>
</body>
</html>
The Javascript that implements the shared worker in shared.js
:
var ws = null
var url = "ws://" + location.hostname + ":6080"
self.addEventListener("connect", function(e) {
var port = e.ports[0]
port.addEventListener("message", function(e) {
if (e.data === "start") {
if (ws === null) {
ws = new WebSocket(url);
port.postMessage("started connection to " + url);
} else {
port.postMessage("reusing connection to " + url);
}
}
}, false);
port.start();
}, false);
I have verified that this works in Chrome 52.