Pages

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.

11 comments:

  1. I appreciate the effort of the blogger. I have one small question which is related to html5. If you could help me out then it would be really helpful. How is the page structure in html5 is different from html4?
    html5 training in chennai

    ReplyDelete
    Replies
    1. Java Training Institutes Java Training Institutes
      Java Spring Hibernate Training Institutes in Chennai J2EE Training Institutes in Chennai J2EE Training Institutes in Chennai Core Java Training Institutes in Chennai Core Java Training Institutes in Chennai

      Hibernate Online Training Hibernate Online Training Hibernate Training in Chennai Hibernate Training in Chennai Java Online Training Java Online Training Hibernate Training Institutes in ChennaiHibernate Training Institutes in Chennai

      Delete
  2. The best thing about HTML5 is that it allows the developers to embed the video files, audio files, and high quality graphics without any third party applications.
    html5 training institutes in chennai | Fita Chennai reviews

    ReplyDelete

  3. I have completely read your post and the content is crisp and clear.Thank you for posting such an informative article, I have decided to follow your blog so that I can myself updated.
    Android training in Chennai | Android course in Chennai | Android training institute in Chennai

    ReplyDelete