Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
SharedWorker in React

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!