summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/webmessaging/broadcastchannel/resources/worker.js
blob: ee2d51a254256761626e9d3e7743dad89caf0233 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
importScripts("/common/gc.js");

var c;

async function handler(e, reply) {
  if (e.data.ping) {
    c.postMessage(e.data.ping);
    return;
  }
  if (e.data.blob) {
    (() => {
      c.postMessage({blob: new Blob(e.data.blob)});
    })();
    await garbageCollect();
  }
  c = new BroadcastChannel(e.data.channel);
  let messages = [];
  c.onmessage = e => {
      if (e.data === 'ready') {
        // Ignore any 'ready' messages from the other thread since there could
        // be some race conditions between this BroadcastChannel instance
        // being created / ready to receive messages and the message being sent.
        return;
      }
      messages.push(e.data);
      if (e.data == 'done')
        reply(messages);
    };
  c.postMessage('from worker');
}

onmessage = e => handler(e, postMessage);

onconnect = e => {
  let port = e.ports[0];
  port.onmessage = e => handler(e, msg => port.postMessage(msg));
};