Search code examples
javascriptreactjsweb-worker

Why doesn't this webworker respond to a posted message?


I am working on a React project, and I have this code:

Here, I initialize a web-worker and post a message when the Documentation component is loaded.

function Documentation() {
  const [result, setResult] = useState(null);

  useEffect(() => {
    console.log('ran');
    const worker = new Worker('../../Workers/SolveWorker.js');

    worker.postMessage({ type: 'start', data: [5, 10] });

    console.log(worker);


    return () => {
      worker.terminate();
    };
  }, []);
  
  ...

Inside ../../Workers/SolveWorker.js, I have my worker respond to an event:

/* eslint-disable-next-line no-restricted-globals */
self.onmessage = function (e) {
  console.log("Worker: Message received from main script");
};

When I load this component, my message appears to be posted but I never receive a response from the web worker. I've looked at the API but have been unable to figure out what I am doing wrong. Additionally, I get this error: SolveWorker.js:1 Uncaught SyntaxError: Unexpected token '<' (at SolveWorker.js:1:1)

I believe this is somehow relating to my HTML file (when I click this error in chrome dev tools it opens up my HTML), but I’m not really sure in what way.

Any help is appreciated.


Solution

  • When you call const worker = new Worker('../../Workers/SolveWorker.js'); your browser will go try to fetch '../../Workers/SolveWorker.js'. The path is relative to the document root (i.e. where your index.html file is located, sounds like /public in your case) like it would be for a script tag src, not the Javascript file where the worker is created.

    Alternatively, you can use a rollup plugin to inline workers in which case your file path would be correct because it would go through the normal node resolution algorithm at build time.