<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test that current inner window checks are correct after navigations/discards</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>

<iframe id="frame"></iframe>

<script type="application/javascript">
"use strict";

const TEST_FILE = "file_current_inner_window.html";
const BASE_PATH = location.pathname.replace(/[^\/]+$/, "");

let frame = document.getElementById("frame");

function loadInFrame(url) {
  return new Promise(resolve => {
    frame.addEventListener("load", resolve, { once: true });
    frame.contentWindow.location = url;
  });
}

add_task(async function() {
  await loadInFrame(TEST_FILE);

  // Store the check function from the window before we navigate. After that,
  // its bare word property accesses will continue referring to the same inner
  // window no matter how many times the frame navigates.
  let check1 = frame.contentWindow.isCurrentWinnerWindow;
  ok(check1(),
     "Initial inner window should be current before we navigate away");

  await loadInFrame(`http://example.com/${BASE_PATH}/${TEST_FILE}`);
  ok(!check1(),
     "Initial inner window should no longer be current after we navigate away");
  await SpecialPowers.spawn(frame, [], () => {
    Assert.ok(this.content.wrappedJSObject.isCurrentWinnerWindow(),
              "Remote inner window should be current after before we navigate away");
  });

  await loadInFrame(TEST_FILE);
  ok(!check1(),
     "Initial inner window should still not be current after we back to current process");
  let check2 = frame.contentWindow.isCurrentWinnerWindow;
  ok(check2(),
     "Second in-process inner window should be current before we remove the frame");

  frame.remove();
  ok(!check1(),
     "Initial inner window should still not be current after we remove the frame");
  ok(check2(),
     "Second in-process inner window should still be current after we remove the frame");
});
</script>
</body>
</html>
