aparna aparna - 4 years ago 99
Javascript Question

Web Workers and Reference Error

I have a text area which has java script code:

<textarea id="jsCode">alert("done"); </textarea>


I have code that creates a Worker to eval this javascript code. Here the value of jsCode is obtained as - alert("done");

var jsCode=$("#jsCode").val();

var worker = new Worker("worker.js");
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);

worker.postMessage(jsCode);


My worker.js is as follows:

self.addEventListener('message', function(e) {
eval(e.data);
self.postMessage(e.data);
}, false);


When I run this file I get a Reference Error. I assume this is happening when we're trying to evaluate the alert as passed as part of the e.data which was obtained from the text area. How is it possible to do such evaluation?

Uncaught ReferenceError: alert is not defined

Also not able to view any console message that are posted inside the worker so I'm unable to debug (Using Chrome and developer tools)

Answer Source

The WebWorker has no access to the original document or window object. Hence it has no access to the respective functions.

Some of the functions are mirrored inside the WebWorker, but alert() is not one of them. Would not make sense, as the WebWorker has no access to any form of visual output anyways.

Depending on the browser, the same holds true for the console object. There is some work, though, to change this. See, e.g., this Firefox bug report.

As for debugging, you have at least to choices:

  • define an onerror handler inside the WebWorker to catch all errors, and send a (serialized) error message to the original document for output.

  • According to this blog entry you can debug WebWorker directly using the Chrome Dev Tools.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download