Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you assign a name to a Web Worker?

If you start two web workers that use the same JavaScript file, there is no way in Firefox to distinguish them in about:debugging#workers. You get two identical entries (listed under "Other Workers").

For debugging, it would be convenient to assign names to web workers. For instance, in Java there is Thread#setName. Is there something equivalent in JavaScript's web worker API?

like image 711
Philipp Claßen Avatar asked Jul 03 '17 12:07

Philipp Claßen


2 Answers

The Worker() constructor takes an optional options argument which can contain a name property, for example:

let workerOne = new Worker(URL, {
  'name' : 'nameOfWorkerOne'
}),
    workerTwo = new Worker(URL, {
  'name' : 'nameOfWorkerTwo'
});

Nice, I overlooked that. Do you know if it is portable?

There is a link to the specification on the MDN page I linked above. If you follow the white rabbit you will see that the options argument is part of the spec.

It can be read as name property of the global object in the worker, e.g. in a debugger.

like image 95
the8472 Avatar answered Nov 09 '22 17:11

the8472


In summary, I would recommend to combine both approaches provided by the8472 and Patrick Evans to get the best debugging experience:

  1. Setting the name via the web worker API (for details, see the8472's answer)
  2. Adding a dummy parameter to the URL, so it will show up in Firefox (for details, see Patrick Evans' answer)

For example, instead of

let worker = new Worker(url);

write something like this

let worker = new Worker(`${url}?name=SomeContext`, { name: 'Some useful context' });

At least in Firefox 54, the optional name parameter is not shown in the worker overview. Therefore, extending the URL is still useful. On the other hand, using the API (even though it is not currently used by Firefox from what I see) seems like a good idea when you look at the documentation:

name: A DOMString specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.

I wish browsers would show the name in the worker overview (e.g., about:debugging#workers in Firefox), which would render the URL extension workaround obsolete.

Note that by modifying the URL the browser may end up doing extra work and may even fetch extra data over the network. Depending on your use case, this could be a disadvantage if you intend to use the workaround in production. In my specific case, the overview is not an issue as the code is statically served (it is part of a browser extension).

like image 1
Philipp Claßen Avatar answered Nov 09 '22 17:11

Philipp Claßen