Search code examples
javascripthtmlmultithreadingwebweb-worker

Web Worker - Is it possible to subscribe / catch the init function from inside the Worker js?


When creating new Worker instance with a name, for example:

// index.js
const myWorker = new Worker('./worker.js', { name: 'myWorker' });

Is it possible to subscribe/catch the initialization from inside worker.js and then, for example, grab its name?

// worker.js
const oninit = options => {
  console.log(options.name); // ==> logs "myWorker"
};

I can't find such option... Am I getting the concept wrong or something?


Solution

  • I guess "init" happens when the worker is loaded / executed, so whatever you invoke directly in it runs immediately. The name (DedicatedWorkerGlobalScope.name) from the options should be readable as self.name, so simply calling

    // worker.js
    console.log(self.name);
    

    should do the trick (provided your worker's environment has working console).