javascripthtmlweb-worker

Any standard mechanism for detecting if a JavaScript is executing as a WebWorker?


A WebWorker executes with a scope completely separate from the 'window' context of traditional JavaScript. Is there a standard way for a script to determine if it is, itself, being executed as a WebWorker?

The first 'hack' I can think of would be to detect if there is a 'window' property in the scope of the worker. If absent, this might mean we are executing as a WebWorker.

Additional options would be to detect properties not present in a standard 'window' context. For Chrome 14, this list currently includes:

FileReaderSync
FileException
WorkerLocation
importScripts
openDatabaseSync
webkitRequestFileSystemSync
webkitResolveLocalFileSystemSyncURL

Detecting WorkerLocation seems like a viable candidate, but this still feels a bit hackish. Is there a better way?

EDIT: Here is the JSFiddle I used to determine properties present in the executing WebWorker that are now in 'window'.


Solution

  • The spec says:

    The DOM APIs (Node objects, Document objects, etc) are not available to workers in this version of this specification.

    This suggests checking for the absence of document is a good way to check you're in a worker. Alternatively you could try checking for the presence of WorkerGlobalScope?