Javascript Web Workers: Chrome 5 Now Supports Complex Messages

After updating to Chrome 5 (specifically 5.0.375.55) last night I immediately ran some tests to see if the Web Worker API had been updated to support postMessage() arguments of types other than string.


Turns out, it had.


Here’s the test, plus the results:https://gist.github.com/414901


renderer.html

<script src="renderer.js"></script>

renderer.js


var worker = new Worker('worker.js'); worker.addEventListener('message', function (event) { var message = event.data; console.group('Message Received'); console.log( message ); console.groupEnd(); }, false); // TEST VALID JSON ARG worker.postMessage({ 'renderer-process': 'Hello Worker Process' }); // TEST OBJECT ARG worker.postMessage({ rendererProcess: 'Hello Worker Process', resultOf: (function () { return 'the result'; })() }); // TEST ANOTHER THREAD SAFE OBJECT ARG var obj = new Object(); obj.isArray = [ 1,2,3,4,5 ]; obj.isString = 'Foo bar baz', obj.resultOf = (function () { return 'returned from self executing function'; })(); worker.postMessage(obj); // TEST STRING ARG worker.postMessage('Hello Worker Process'); // TEST ARRAY ARG worker.postMessage([ 1, 2, 3, 4 ]); // TEST BOOLEAN ARG worker.postMessage(false); // TEST BOOLEAN ARG worker.postMessage(true);

worker.js

self.addEventListener('message', function (event) {
  var message = event.data;


  //  IF BOOLEAN
  if ( typeof message === 'boolean' ) {
    message = 'boolean: ' + message.toString();
  }
  //  ALL OTHER MESSAGE TYPES
  else {

    //  IF STRING OR ARRAY
    if ( message.length ) {
      //  IF STRING
      if ( typeof message == 'string' ) {
        message += ', Hello Renderer Process';
      }
      else {
        var len     = message.length + 1,
            floor   = len,
            ceil    = floor * 2;


        for ( ; floor < ceil; floor++ ) {
          message.push(floor);
        }
      }
    }
    //  IF OBJECT
    else {
      message['worker-process'] = 'Hello Renderer Process';
    }
  }

  this.postMessage(message);


}, false);

results.console.js

// Results

Message Received
  Object
    renderer-process: "Hello Worker Process"
    worker-process: "Hello Renderer Process"
    __proto__: Object

Message Received
  Object
    rendererProcess: "Hello Worker Process"
    resultOf: "the result"
    worker-process: "Hello Renderer Process"
    __proto__: Object


Message Received
  Object
    isArray: Array (5)
      0: 1
      1: 2
      2: 3
      3: 4
      4: 5
      length: 5
    isString: "Foo bar baz"
    resultOf: "returned from self executing function"
    worker-process: "Hello Renderer Process"

Message Received
  Hello Worker Process, Hello Renderer Process

Message Received
  [1, 2, 3, 4, 5, 6, 7, 8, 9]

Message Received
  boolean: false

Message Received
  boolean: true


I did small bit of research and could only come up with this ticket:

Issues in passing parameters to HTML5 worker threads

EditIn the time since this was originally published, Chrome, Safari & Opera now support complex JSON messages.

Comments

We moved off of Disqus for data privacy and consent concerns, and are currently searching for a new commenting tool.

  1. @Irakli I checked out your site and you have a really impressive portfolio of work, so I’m not sure why you’ve left a comment like this.

    All JSON is an object. All Objects are not JSON.

    I’ve added an additional test, that used the new Object constructor… is that acceptable for you? I don’t think you can argue that a variable created with new Object() is not an object.

    Thanks for the feedback.

  2. I am brand new to web workers but I’m already loving them. Especially seeing as you can now return more than e.g. ‘I is tha hello world str’.

    Are there (m)any examples of hooking up to the web sql(lite) db using a worker?

    Let’s hope my brain doesn’t melt and my eyes don’t bleed out of their sockets before I get all of this new information in 🙂

  3. Hi,

    Great post, great information. Arrived here via an Ajaxian post. Web workers is great news, and the browser support for it is very exciting!

    I am curious about your first example code, however. Specifically, the line that assigns obj.resultOf to an anonymous function. Because the closure is immediately executed, it would appear that the typeof the obj.resultOf property would be === string, since the result of the immediate function is also === string. I haven’t tested to see if simply obj.resultOf = function (){ return \”string\”;}; works as expected, but that would be the assignment of a function, as otherwise it’s simply an obfuscated way to assign a string value to the variable.

    Or perhaps I missed the point entirely? 😉

    • The closure is supposed to evaluate, hence it’s returned value saying so…

      obj.resultOf = function (){ return \u201cstring\u201d;}

      is not thread safe and would not work, which is why I didn’t use it as an example

Contact Us

We'd love to hear from you. Get in touch!

Mail

P.O. Box 961436
Boston, MA 02196