<!DOCTYPE html>
<title>Service Worker: postMessage via MessagePort to Client</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.sub.js"></script>
<script>
promise_test(t => {
    var script = 'resources/postmessage-msgport-to-client-worker.js';
    var scope = 'resources/blank.html';
    var port;

    return service_worker_unregister_and_register(t, script, scope)
      .then(registration => {
          add_completion_callback(() => registration.unregister());
          return wait_for_state(t, registration.installing, 'activated');
        })
      .then(() => with_iframe(scope))
      .then(frame => {
          t.add_cleanup(() => frame.remove());
          return new Promise(resolve => {
              var w = frame.contentWindow;
              w.navigator.serviceWorker.onmessage = resolve;
              w.navigator.serviceWorker.controller.postMessage('ping');
            });
        })
      .then(e => {
          port = e.ports[0];
          port.postMessage({value: 1});
          port.postMessage({value: 2});
          port.postMessage({done: true});
          return new Promise(resolve => { port.onmessage = resolve; });
        })
      .then(e => {
          assert_equals(e.data.ack, 'Acking value: 1');
          return new Promise(resolve => { port.onmessage = resolve; });
        })
      .then(e => {
          assert_equals(e.data.ack, 'Acking value: 2');
          return new Promise(resolve => { port.onmessage = resolve; });
        })
      .then(e => { assert_true(e.data.done, 'done'); });
  }, 'postMessage MessagePorts from ServiceWorker to Client');
</script>
