Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

html - 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'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...