I have done some testing to find out the answer to this in practice.
Firefox does not yet support creating WebSocket connections from Web Workers: https://bugzilla.mozilla.org/show_bug.cgi?id=504553 So Firefox is not relevant until that bug is resolved.
IE 10 doesn't have support for Shared Web Workers so it's not relevant either. So that leaves Chrome.
Here is an example to test shared web workers.
First the HTML:
<!DOCTYPE html>
<html>
<body>
<a href="shared.html">reload page</a>
<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>
Then the implementation of the shared worker itself in shared.js
:
var connections = 0;
self.addEventListener("connect", function(e) {
var port = e.ports[0];
connections ++;
port.addEventListener("message", function(e) {
if (e.data === "start") {
var ws = new WebSocket("ws://localhost:6080");
port.postMessage("started connection: " + connections);
}
}, false);
port.start();
}, false);
Test results in Chrome 20 (the answer):
When the page is loaded simultaneously in two separate tabs, the connection count grows each time one of the pages is reloaded or the self-referential link is clicked.
If only a single instance of the page is loaded then the connection count never changes when the page is reloaded or the link is clicked.
So, in Chrome 20: Shared Web Workers do not persist across page reloads and link navigation clicks.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…