Sunday, February 7, 2010

Logging With HTML5 WebWorkers

I'm converting some of my code for Art Evolver to use HTML5 WebWorkers instead of doing CPU-intensive operations in the main UI thread (cardinal sin, that is). It went pretty smoothly but I ran into a small problem while debugging: you can't log messages to console.log from a WebWorker. I assume this is for security reasons.

I worked around this by calling postMessage() from my WebWorker to get the log message into the browser window where it could be logged:

// inside render-worker.js
function log(msg) {
  postMessage("log: " + msg);
}
and in the code that calls the worker, I added this to the onmessage callback:
// inside UI code running in the main browser window
worker.onmessage = function(e) {
  if (e.data.indexOf("log:") == 0) {
    window.console.log(e.data);
    return;
  }

  // assume it's not a log message, JSON.parse() it,
  // or do other stuff with it here.
}

Voila- logging from inside a WebWorker. Totally a hack, but it worked for me in a pinch.

0 comments:

Post a Comment