Do Shared Web Workers persist across a single page reload, link navigation

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="https://stackoverflow.com/questions/9336774/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.

Leave a Comment