As discussed in this question and this bug, shared workers have been badly broken in Firefox since version 57. Basically, the "shared" part is missing. The way it's supposed to work is that creating a shared worker with the same worker script in two tabs will only create one instance of the worker, but in Firefox it creates two instances.
Anyone using shared workers is familiar with this type of problem, because shared workers are not supported in IE, Edge, or Safari. So you have to make due with web workers. That's fine, I could do the same thing with buggy Firefox versions, except... how do I do feature detection for this, so I can send the non-shared version of my worker in this case?
I figured I could use a worker like this and see if the counter resets when it shouldn't:
var count = 0; onconnect = function (e) { var port = e.ports[0]; port.postMessage(count); count += 1; }
My first idea was to just create two shared workers in the same page and see if the counter is 0 for both of them. But it's not. This:
function createWorker(url, workerNum) {
var worker = new SharedWorker(url);
worker.port.onmessage = function (e) {
console.log("Worker " + workerNum + ": " + e.data);
};
}
for (var i = 0; i < 2; i++) {
createWorker("worker.js", i);
}
produces the correct output:
Worker 0: 0
Worker 1: 1
Then I thought maybe I could run that script in two iframes within the same page, but no dice, this is also correct:
Worker 0: 0
Worker 1: 1
Worker 0: 2
Worker 1: 3
If I open the page in two tabs, I can see the problem - the counter resets to 0 in each tab. But if it requires users to open a new tab, it's not very useful feature detection. Even worse, the bug seems to be intermittent. Sometimes the counter does correctly persist across tabs! So this approach is not going to work...
This seems like a very nasty bug to do feature detection for. Does anyone have any ideas? Or am I stuck parsing user agent strings?