Reputation: 14906
Why is Shared Worker dead on reloading page? It must've revived. How can I fix this issue?
var port = new SharedWorker('/app/worker-5n1261e73b.js').port;
port.onmessage = function(e){
console.log(e.data);
};
port.start();
onconnect = function(e){
var port = e.ports[0];
port.onmessage = function(e){
console.log(e.data);
};
port.start();
port.postMessage('Connected');
};
Upvotes: 4
Views: 1713
Reputation: 699
When a page is reloaded the javascript is executed again and so is the code that creates the connection to your SharedWorker.
The onconnect()
event handler, in your Sharedworker, does not know whether the tab was reloaded or whether it is an entirely new tab, so it just registers the tab as a new connected port, stopping the communication with the previous tab port (if the page was reloaded). In other words, the reloaded page got a new port number for the Sharedworker.
If you only had one tab open at that time, for sure the Sharedworker is stopped and recreated when reloading the page, but if you had more than one page opened by that time, the Sharedworker does not stop working because of the other live connections.
Upvotes: 4