Search code examples
javascripthtmlweb-worker

Identifying when a JS script is running as a Worker


I have a script which can be run either directly or, when available in the browser, as a Web Worker. I'd like to run a portion of this script only when run as a worker; so my question is, how can a script identify itself as being run this way?

I can't see anything in the spec that would allow this to happen; am I missing something obvious?


Solution

  • In the following :

    <html>
    <head>
    <title>Worker</title>
    </head>
    <body>
    </body>
    <script >
      var w = new Worker ('worker.js');
      w.onmessage = function (e) {
        document.body.innerHTML += '<br>' + 'WORKER : ' + e.data;
      };
    </script>
    <script src='worker.js'></script>
    </html>
    

    worker.js is invoked both as a script and as a worker.

    worker.js contains :

      var msg = 'postMessage is ' + postMessage.toString () + 
              ', self.constructor is ' + self.constructor;
      try {
        postMessage (msg);
      } catch (e) {
        document.body.innerHTML += '<br>SCRIPT : ' + msg;
      }  
    

    In the worker environment, the postMessage succeeds, in the script environment it fails because either it is undefined or, in a browser, it requires a second argument.

    Output is :

    chrome :

    SCRIPT : postMessage is function () { [native code] }, self.constructor is function DOMWindow() { [native code] } 
    WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function DedicatedWorkerContext() { [native code] }
    

    firefox :

    SCRIPT : postMessage is function postMessage() { [native code] }, self.constructor is [object Window]
    WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function DedicatedWorkerGlobalScope() { [native code] }
    

    opera:

    WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function Object() { [native code] }
    SCRIPT : postMessage is function postMessage() { [native code] }, self.constructor is function Object() { [native code] }
    

    All under Ubuntu.