Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
Graham Avatar asked Nov 21 '25 22:11

Graham


1 Answers

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.

like image 136
HBP Avatar answered Nov 24 '25 14:11

HBP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!