I am using web workers in my React application with a helper class that looks like this:
export class WebWorker {
constructor(worker) {
const code = worker.toString();
const blob = new Blob(["(" + code + ")()"]);
return new Worker(URL.createObjectURL(blob));
}}
The worker looks something like:
export default () => {
self.addEventListener('message', function (e) {
switch (e.data.event) {
case 'start':
// Start back ground task
break;
case 'stop':
// Stop background task
break;
}
}, false);
Then I am able to create the worker using
let sessionWorker = new WebWorker(SessionWorker);
sessionWorker.postMessage({event: "start"})
This works fine, however I now need to use a SharedWorker and I am having trouble getting it to work. All of the resources I've found show regular web workers. There is this SO Question Using Shared Worker in React but it doesn't work for me. It actually looks identical to my regular WebWorker code, but this doesn't work because SharedWorkers require that you implement an onconnect function, and I don't understand how to do that. Non-react examples that I've found show the worker script as:
onconnect = function(e) {
var port = e.ports[0];
port.onmessage = function(e) {
var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
port.postMessage(workerResult);
}
}
but if I put that in my worker js file and follow the same pattern using the WebWorker helper, the worker.toString() just returns [object Window] and it never gets executed. I don't understand how to create an 'onconnect' function that will get called. I've tried variations like this:
import React from 'react';
self.onconnect = (e) => {
var port = e.ports[0];
console.log("test log");
port.onmessage = function(e) {
console.log("Message received ", e)
port.postMessage("test");
}
}
export default self;
Ultimately nothing works for me. Clearly I do not understand exports at all in Javascript. If I just export a function called onconnect it never gets called, clearly the onconnect has to belong to some sort of class-like context (like Window or Self) but I don't understand what is needed
Thankyou, Troy.