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

后端 未结 5 1678
遇见更好的自我
遇见更好的自我 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:29

    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:

    // other declarations here
    ,isNode = ("undefined" !== typeof global) && ('[object global]' === Object.prototype.toString.call(global))
    // http://nodejs.org/docs/latest/api/all.html#all_cluster
    ,isNodeProcess = isNode && !!process.env.NODE_UNIQUE_ID
    ,isWebWorker = !isNode && ('undefined' !== typeof WorkerGlobalScope) && ("function" === typeof importScripts) && (navigator instanceof WorkerNavigator)
    ,isBrowser = !isNode && !isWebWorker && ("undefined" !== typeof navigator) && ("undefined" !== typeof document)
    ,isBrowserWindow = isBrowser && !!window.opener
    ,isAMD = "function" === typeof( define ) && define.amd
    ,supportsMultiThread = isNode || "function" === typeof Worker
    ,isThread = isNodeProcess || isWebWorker
    // rest declarations here..
    

提交回复
热议问题