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

Drew Wilson atwilson at google.com
Thu Feb 25 09:58:37 PST 2010


BTW, I think it's valuable to point out in the example that
MessageEvent.target == the port that received the message (so we don't need
to use a closure as in the example below - just use
event.target.postMessage()).

This is slightly outside the scope of this discussion, but I've heard
rumblings about the (w3c?) community collectively developing some sort of
unified test suite for HTML5 APIs like SharedWorkers. Is someone driving
that effort forward? I say this because I've tried to put together an ad hoc
test suite for the WebKit implementation, but I'm sure it's missing a number
of obscure cases, so having a canonical suite would be really valuable to
ensure compatibility.

-atw

On Thu, Feb 25, 2010 at 12:41 AM, Simon Pieters <simonp at opera.com> wrote:

> On Tue, 23 Feb 2010 21:36:15 +0100, Simon Pieters <simonp at opera.com>
> wrote:
>
>  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');
>>   }
>> }
>>
>
> The worker script could be modified in step 3 as follows to make it clear
> that the script is in fact shared:
>
> test.js
> var i = 0;
> onconnect = function(e) {
>  i++;
>
>  var port = e.ports[0];
>  port.postMessage('hello, ' + i);
>
>  port.onmessage = function(e) {
>    port.postMessage('pong');
>  }
> }
>
> --
> Simon Pieters
> Opera Software
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.whatwg.org/pipermail/whatwg-whatwg.org/attachments/20100225/78be9c9e/attachment-0001.htm>


More information about the whatwg mailing list