用于检测JavaScript是否作为WebWorker执行的任何标准机制? [英] Any standard mechanism for detecting if a JavaScript is executing as a WebWorker?
问题描述
WebWorker使用与传统JavaScript的窗口上下文完全分离的范围执行。是否有一种标准方法可以让脚本确定它本身是作为WebWorker执行的?
我能想到的第一个'黑客'是检测工作者范围内是否有'窗口'属性。如果缺席,这可能意味着我们正在作为WebWorker执行。
其他选项将用于检测不存在于标准窗口上下文中的属性。对于Chrome 14,此列表目前包括:
FileReaderSync
FileException
WorkerLocation
importScripts
openDatabaseSync
webkitRequestFileSystemSync
webkitResolveLocalFileSystemSyncURL
检测WorkerLocation看起来像是一个可行的候选人,但这仍然感觉有点ha。。有没有更好的办法?
编辑:这里是我曾经用过的JSFiddle确定正在执行的WebWorker中现在处于窗口中的属性。
spec 说:
在此版本的规范中,DOM API(节点对象,Document对象等)不适用于工作人员。
这表明检查是否存在文档
是检查您是否在工作中的好方法。或者,您可以尝试检查是否存在 WorkerGlobalScope
?
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'.
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
?
这篇关于用于检测JavaScript是否作为WebWorker执行的任何标准机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!