<!DOCTYPE html>
<html>
  <head>
    <script src="/resources/testharness.js"></script>
    <script src="/resources/testharnessreport.js"></script>
    <script src="/resources/testdriver.js"></script>
    <script src="/resources/testdriver-vendor.js"></script>
    <script>
      function childReady() {
        return new Promise((resolve) => {
          window.onmessage = resolve;
        });
      }

      const handlers = ['beforeunload', 'pagehide', 'unload'];
      for (let handler of handlers) {
        promise_test(async (test) => {
          let popup;

          // Open a popup that has a portal, wait for both to be loaded.
          {
            await test_driver.bless('Open a popup', () => {
              popup = open(`resources/portal-activate-in-handler.html?${handler}`,
                           '_blank');
            });
            await childReady();
          }

          // We need the exception type below to ensure the activate() call
          // throws but the popup global may be gone by then so stash it here.
          const exception_type = popup.DOMException;

          // Navigate the popup away.
          const cur_path = popup.location.pathname;
          popup.location = 'resources/blank-host.html';

          // We need to wait until the handler is called but because of the
          // nature of these handlers, we can't reliably communicate with the
          // popup while they're running so we use a promise established
          // earlier to wait until a time we know the portal has been activated
          // and the returned promise stored on this global.
          await window.handler_called_promise;
          assert_not_equals(typeof(window.portal_promise), 'undefined',
                            'Portal.activate() must be called');

          // The popup should have called activate from the handler, and placed
          // the promise returned from that call into this window in the
          // |portal_promise| variable. We expect that this call should reject,
          // however, if it does activate, it's timing dependent whether the
          // handler will be run to completion so we may never fulfil the
          // promise. In that case timeout and fail the test.
          {
            test.step_timeout(() => {
              assert_unreached('Activation didn\'t fulfil.');
            }, 3000);

            await promise_rejects_dom(test,
                                      "InvalidStateError",
                                      exception_type,
                                      window.portal_promise,
                                      "Portal activation must fail.");
          }
          popup.close();
        }, `cannot activate portal from ${handler}`);
      }
    </script>
  </head>
  <body>
  </body>
</html>
