Thursday, 9 May 2013

HTML5 Shared Worker

In the last blog, we have seen how dedicated web workers are implemented in HTML5. This blog is about another worker category which is called Shared Worker.

Shared worker configuration


<title>Shared worker Example</title>
<p id="message"></p>
  var worker = new SharedWorker('sharedworker.js');
  var message = document.getElementById('message');
  worker.port.onmessage = function(event) { 
    message.textContent =;


onconnect = function(e) {
  var port = e.ports[0];
  port.postMessage('Welcome to Shared Worker programming!');
Now we will see, how 2 different pages connect to the same worker. To test that, you can add test2.html by including sharedworker.js, in the same way as done in test1.html.
The WorkerGlobalScope common interface

interface WorkerGlobalScope : EventTarget {
  readonly attribute WorkerGlobalScope self;
  readonly attribute WorkerLocation location;

  void close();
           attribute EventHandler onerror;
           attribute EventHandler onoffline;
           attribute EventHandler ononline;
WorkerGlobalScope implements WorkerUtils;
location will return the absolute URL of the script that was used to initialize the worker.
error event can be used to handle all errors.
 worker.onerror = function(error) {
      console.log("Error is caught "+error.message);
      throw error;
Shared worker can be used to have a client to client communication since the worker data is shared across all the clients.



No comments:

Post a Comment