<!doctype html>
<title>
  Sandboxed Cross-Origin-Opener-Policy popup should cut the opener if necessary
</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/dispatcher/dispatcher.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<script src="/common/utils.js"></script>
<script src="resources/common.js"></script>
<body>
<script>
const executor_path = "/common/dispatcher/executor.html?pipe=";
const coop_same_origin_header =
  '|header(Cross-Origin-Opener-Policy,same-origin)';
const coop_unsafe_none_header =
  '|header(Cross-Origin-Opener-Policy,unsafe-none)';

function getExecutorPath(uuid, origin, coop_header) {
  return origin.origin + executor_path + coop_header  + `&uuid=${uuid}`;
}

[
  "allow-popups allow-scripts allow-same-origin",
  "allow-popups allow-scripts",
].forEach(sandboxValue => {
  async_test(t => {
    // Set up dispatcher communications.
    const iframe_token = token();
    const popup_token = token();
    const main_frame_token_for_popup = token();
    const main_frame_token_for_iframe = token();

    // Create a sandboxed iframe.
    const iframe = document.createElement("iframe");
    iframe.sandbox = sandboxValue;
    iframe.src = getExecutorPath(iframe_token, SAME_ORIGIN,
                                 coop_unsafe_none_header);
    document.body.append(iframe);
    t.add_cleanup(() => iframe.remove());

    // Open a COOP popup from the sandboxed iframe.
    const popup_url = getExecutorPath(popup_token,
    SAME_ORIGIN,
    coop_same_origin_header);
    send(iframe_token, `window.popup = window.open('${popup_url}')`);

    // This should fail. We ping the popup, if we get an answer it loaded.
    send(popup_token, `
    send('${main_frame_token_for_popup}', 'Popup loaded');
    `);
    receive(main_frame_token_for_popup)
    .then(t.unreached_func("A COOP popup was created from a sandboxed frame"));

    // We delay probing the popup.closed property to give it time to settle.
    t.step_timeout(() => {
    send(iframe_token,
    `send('${main_frame_token_for_iframe}', window.popup.closed);`);
    }, 1500);
    receive(main_frame_token_for_iframe)
    .then(t.step_func_done(data => assert_equals(data, "true")));

  }, `<iframe sandbox="${sandboxValue}"> ${document.title}`);
});
</script>
</body>
