I'd like to set up my library to "just work" as a Web Worker if spun up in a new Worker()
. To do so I need to attach an event listener on self
to receive messages.
If my script has been included inside another developer's Web Worker using an importScripts()
, how do I know when I'm a third party and should not attach an event listener on self to receive messages?
You may try like this using WorkerGlobalScope :
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
// code
} else {
// code
}
ie, you may check for the absence of document
to check you're in a worker.
Also the specs says that:
The DOM APIs (Node objects, Document objects, etc) are not available to workers in this version of this specification.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.