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

后端 未结 5 1682
遇见更好的自我
遇见更好的自我 2020-12-14 19:01

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, its

5条回答
  •  天命终不由人
    2020-12-14 19:22

    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:

    this.DedicatedWorkerGlobalScope?this.__proto__ === this.DedicatedWorkerGlobalScope.prototype:false
    
    this.WorkerGlobalScope?this.__proto__.__proto__ === this.WorkerGlobalScope.prototype:false // works for shared workers too
    
    this.constructor === this.DedicatedWorkerGlobalScope //or SharedWorkerGlobalScope
    
    !(this.DedicatedWorkerGlobalScope === undefined)
    
    !(this.DedicatedWorkerGlobalScope === undefined)
    

    You can also use self § instead of this, but since this can't be set, its neater.


    I prefer:

    this.DedicatedWorkerGlobalScope !== undefined
    

    Of course, if you only have worker context and window context, you can do the inverse tests for window context. Eg this.Window === undefined.

提交回复
热议问题