[whatwg] Web Workers: include simple example for shared workers

The Web Worker's first example of shared workers is quite involved and not  
so easy to follow if you haven't dealt with shared workers before. For  
someone wanting to experiment with shared workers, it's easier to grasp  
how things work by doing something very basic first. It would be useful if  
the spec had an example for this.

The example should include:

* How to create a shared worker.
* How to listen for messages from the worker. Note explicitly that the  
listener is on the port -- not the worker object.
* If addEventListener('message',...) is used, note that start() needs to  
be called.
* In the shared worker, show how to listen for connect events, how to  
listen for messages on the port, how to post messages back. Note  
explicitly that postMessage needs to be called on the 'connect' event's  
ports[0]; not the 'message' event's ports[0].
* When all that is working, throw in another browsing context that  
connects to the same worker.


Something like this:

step 1.

test.html
<pre id="log">Log:</pre>
<script>
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.onmessage = function(e) { // note: not worker.onmessage!
   log.textContent += '\n' + e.data;
}
</script>


test.js
onconnect = function(e) {
   var port = e.ports[0];
   port.postMessage('hello');
}


step 2.

test.html
<pre id="log">Log:</pre>
<script>
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.addEventListener('message', function(e) {
   log.textContent += '\n' + e.data;
}, false);
worker.port.start(); // note: need this when using addEventListener
worker.port.postMessage('ping');
</script>

test.js
onconnect = function(e) {
   var port = e.ports[0];
   port.postMessage('hello');
   port.onmessage = function(e) {
     port.postMessage('pong'); // not e.ports[0].postMessage!
   }
}


step 3.

test.html
<pre id="log">Log:</pre>
<script>
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.addEventListener('message', function(e) {
   log.textContent += '\n' + e.data;
}, false);
worker.port.start();
worker.port.postMessage('ping');
</script>
<iframe src=other.html></iframe>

other.html
<pre id=log>Inner log:</pre>
<script>
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.onmessage = function(e) {
   log.textContent += '\n' + e.data;
}
</script>

test.js
onconnect = function(e) {
   var port = e.ports[0];
   port.postMessage('hello');
   port.onmessage = function(e) {
     port.postMessage('pong');
   }
}

-- 
Simon Pieters
Opera Software

Received on Tuesday, 23 February 2010 12:36:15 UTC