用于检测JavaScript是否作为WebWorker执行的任何标准机制? [英] Any standard mechanism for detecting if a JavaScript is executing as a WebWorker?

查看:264
本文介绍了用于检测JavaScript是否作为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆