Skip To Main Content

Javascript Web Workers: Chrome 5+ supports new SharedWorker()

Posted by Rick Waldron

Jun 21 2010

In my excitement and haste upon discovering new SharedWorker() support in the Opera 10.60 Beta, I neglected to snoop around the window object of my two favorites, Chrome 5+ and FireFox 3.6+ … WHOOPS! If I had done so, I would’ve discovered, as I did just now, that Chrome 5+ ALSO supports new SharedWorker(). Of course, then I have to test Safari 5 – and yes, it too supports new SharedWorker().


I modified my previous example to try it out in Chrome and Safari (mainly, I removed the call to Firebug Lite). The Gists are available for download here.


The comments will guide you through the process


The inner iframe page:

sharedworker.multi-connect-inner.html

<!DOCTYPE HTML>
<html>
  <head>
    <script src="sharedworker.multi-connect.renderer.js"></script>
  </head>
  <body>
    <pre id="shared-worker-log"></pre>
    <pre id="shared-worker-connection-log"></pre>
  </body>
</html>


The outer page:

sharedworker.multi-connect.outer.html

<!DOCTYPE HTML>
<html>
  <head>
    <title>SharedWorker: Multiple Connections</title>
    <script src="sharedworker.multi-connect.renderer.js"></script>
  </head>
  <body>
    <pre id="shared-worker-log"></pre>
    <iframe style="width:100%" src="sharedworker.multi-connect-inner.html"></iframe>

    <pre id="shared-worker-connection-log"></pre>
  </body>
</html>



The renderer (client side):

sharedworker.multi-connect.renderer.js

document.addEventListener('DOMContentLoaded', function () {

 var SW = {
  worker: (function () {
       // CREATE SHARED WORKER AND RETURN IT
       return new SharedWorker('sharedworker.multi-connect.worker.js');
      })(),
  logTo:  document.getElementById('shared-worker-log'),
  reportTo: document.getElementById('shared-worker-connection-log')
 };


 // REFLECT SW OBJECT
 console.log(SW);

 // LISTEN ON THE SHAREDWORKER'S PORT FOR NEW MESSAGES
 SW.worker.port.addEventListener('message', function(event) {

  // INITIAL CONNECTION
  if ( event.data.connected ) {
   var workerLog = 'ConnectionId #' + event.data.connectionId +
                   ' ' + event.data.pathName +
                   ' - Connected: ' + event.data.connected ;

   // APPEND TO LOG FIELD
   SW.logTo.textContent += "\n" + workerLog;

   return;
  }

  // REPORTED CONNECTION ID #
  if ( event.data.connectionId ) {
   console.log( event.data.connectionId );
  }


  // REPORTING CONNECTIONS TO SHARED WORKER
  if ( event.data.connections ) {
   var connectionPaths = event.data.connections;

   console.log('Total Connections: ' + connectionPaths.length);

   for ( var id in connectionPaths ) {

    if ( id !== 'length' ) {

     var connectionLog = '#' + id + ' ' + connectionPaths[id];

     // WRITE TO CONSOLE
     console.log( connectionLog );

     // APPEND TO REPORT FIELD
     SW.reportTo.textContent += "\n" + connectionLog;
    }
   }
   return;
  }
 }, false);

 // START THE CONNECTION TO SHAREDWORKER
 // REQUIRED WHEN USING "addEventListener()"
 SW.worker.port.start();
 // FIRE CONNECTING MESSAGE TO SHAREDWORKER
 SW.worker.port.postMessage({
  'pathName': location.pathname,
  'connected' : false
 });
}, false);

The worker:

sharedworker.multi-connect.worker.js

var Connection = {
 count:    0,
 isConnected: false,
 paths:    {
  length: 0
 }
};

self.addEventListener('connect', function (event) {

 var port = event.ports[0];

 port.addEventListener('message', function (event) {


  // INCREMENT CONNECTION COUNT
  Connection.count++;

  // REPLY TO RENDERER, CONFIRMING CONNECTION
  port.postMessage({
   'connectionId' : Connection.count
  });

  // STORE A REF TO THE CONNECTING RENDERER PAGE
  Connection.paths[Connection.count] = event.data.pathName;
  Connection.paths.length++;

  // UPDATE CONNECTION TO TRUE
  event.data.connected  = true;

  // UPDATE WITH THIS CONNECTION ID
  event.data.connectionId = Connection.count;

  // REPLY TO RENDERER
  port.postMessage(event.data);


 }, false);

 // REQUIRES `start()` WHEN USING
 // `addEventListener` SYNTAX
 port.start();


 // REPORT CONNECTIONS
 setTimeout(function () {
  port.postMessage({
   'connections' : Connection.paths
  });
 }, 1000);


}, false);

That leaves two browsers to add support… I’m looking at you Firefox 4. IE9 almost isn’t worth mentioning, because while I’m optimistic that it will support new Worker() (because the first preview announcement said it would) – I doubt we’ll get support for new SharedWorker() in the same release. Prove me wrong.

Posted by
Rick Waldron
on June 21st, 2010

Comments

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

Contact Us

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