Debugging web workers

Debugging web workers can be difficult. You don't have access to the window object so you can't call alert() to display a message or console.log() to write out to the browser's JavaScript console. You can't write out a message to the DOM either. You can't even attach a debugger and step through the code. So what's a poor developer to do?

One thing you can do is add an error listener to the worker, so you get notified of any errors inside the worker's thread:

worker.addEventListener("error", function(e)
{
    alert("Error in worker: " + e.filename + ", line:" + e.lineno + ", " + e.message);
});

The event object passed into the error handler contains the filename, lineno, and message fields. From those you can tell exactly where an error happened.

But what if you aren't getting an error, things just aren't working right? First of all, I recommend that you keep the code that does all of the processing for your worker in a separate file, like we did in mandelbrotGenerator.js. This allows you to run the code from your main thread as well as a worker. If you need to debug it you can run it directly from the application and debug as you normally would.

One debugging trick you can use is to define a console object in your web worker that sends messages back to the main thread where they can be logged using the window's console:

var console = {
    log: function(msg)
    {
        self.postMessage({
            type: "log",
            message: msg
        });
    }
};

In your application, you then listen for the message and log it:

worker.addEventListener("message", function(e)
{
    if (e.data.type == "log")
    {
        console.log(e.data.message);
    }
});

Pop quiz

Q1. How do you send data to a web worker?

  1. You can't send data to a worker.
  2. Using the postMessage() method.
  3. Using the sendData() method.
  4. Using the sendMessage() method.

Q2. Which resource in the main thread does a web worker have access to?

  1. The DOM.
  2. The window object.
  3. The document object.
  4. None of the above.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.85.76