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'.
This worked for me
Although post a bit old, adding a couple of generic alternatives What is used in Asynchronous.js library (a library for generic handling of asynchronous/parallel processes, author) is the following:
There's even more:
WorkerNavigator
etc.Unless there's a keyword to detect webworkers, you got to use a variable. (Nothing can stop a rogue script running before your script from setting or replacing variables. )
So, assuming you do not have any rogue scripts running before your script, any of these lines will work:
You can also use
self
§ instead ofthis
, but sincethis
can't be set, its neater.I prefer:
Of course, if you only have worker context and window context, you can do the inverse tests for window context. Eg
this.Window === undefined
.this works for me:
The spec says:
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 ofWorkerGlobalScope
?