<!DOCTYPE html>
<meta charset=utf-8>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>

const SERVICE_WORKER_TEST_CHANNEL_NAME = 'service worker';
const events = [];
const c1 = new BroadcastChannel(SERVICE_WORKER_TEST_CHANNEL_NAME);
const c2 = new BroadcastChannel(SERVICE_WORKER_TEST_CHANNEL_NAME);
c1.onmessage = e => events.push(e);
c2.onmessage = e => events.push(e);

function testCompletion(t) {
  return new Promise((resolve) => {
    c2.addEventListener("message", t.step_func(e => {
      if (e.data == 'from worker') {
        c2.postMessage('from c2');
      } else if (e.data == 'done') {
        assert_equals(events.length, 5);
        assert_equals(events[0].data, 'from worker');
        assert_equals(events[0].target, c1);
        assert_equals(events[1].data, 'from worker');
        assert_equals(events[1].target, c2);
        assert_equals(events[2].data, 'from c2');
        assert_equals(events[3].data, 'done');
        assert_equals(events[3].target, c1);
        assert_equals(events[4].data, 'done');
        assert_equals(events[4].target, c2);
        resolve();
      }
    }));
  });
}

promise_test(async t => {

    const testResults = testCompletion(t);
    const SCRIPT = "resources/service-worker.js";
    const SCOPE = "/webmessaging/broadcastchannel/resources/not-used/";

    const reg = await navigator.serviceWorker.register(SCRIPT, {'scope': SCOPE});
    t.add_cleanup(() => reg.unregister());

    return testResults;
  }, 'BroadcastChannel works in service workers');
</script>
