I've been trying to use a SharedWorker in a Vue application, but faced the error "Failed to fetch a worker script".
I want to use a SharedWorker to get and post messages to WebSocket.
socketworker.js
const API_KEY =
"<my api key>";
const socket = new WebSocket(
`wss://streamer.cryptocompare.com/v2?api_key=${API_KEY}`
);
self.onconnect = e => {
const port = e.ports[0];
socket.addEventListener("message", evt => {
if (evt.data) {
port.postMessage(evt.data);
return;
}
});
};
self.onmessage = e => {
message = e.data;
socket.send(message);
};
api.js
const socketWorker = new SharedWorker("./workers/socketworker.js", {
type: "module",
name: "socketWorker"
});
socketWorker.port.onmessage = e => {
...
}
I faced the same problem for a Vue SPA project and solved using "tabex" lib (https://github.com/nodeca/tabex)
This lib emits events based on localStorage changes for all tabs
This lib has a control of which is the "master" tab, so, you can connect to the websocket only on the master tab and send events to all tabs through the tabex.
The MasterTab control messages from websocket and throws through tabex