<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=837060

When we use Debugger.Object.prototype.executeInGlobal, the 'this' value seen
by the evaluated code should be the WindowProxy, not the inner window
object.
-->
<head>
  <meta charset="utf-8">
  <title>Mozilla Bug 837060</title>
  <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
</head>
<body>
<pre id="test">
<script>
"use strict";

const {addDebuggerToGlobal} = ChromeUtils.importESModule("resource://gre/modules/jsdebugger.sys.mjs");
addDebuggerToGlobal(globalThis);

window.onload = function() {
  SimpleTest.waitForExplicitFinish();

  const iframe = document.createElement("iframe");
  iframe.src = "data:text/html,<script>var me = 'page 1';<\/script>";
  iframe.onload = firstOnLoadHandler;
  document.body.appendChild(iframe);

  function firstOnLoadHandler() {
    const dbg = new Debugger();
    const page1DO = dbg.addDebuggee(iframe.contentWindow);
    iframe.src = "data:text/html,<script>var me = 'page 2';<\/script>";
    iframe.onload = function() {
      const page2DO = dbg.addDebuggee(iframe.contentWindow);
      ok(page1DO !== page2DO, "the two pages' globals get distinct D.O's");
      ok(page1DO.unsafeDereference() === page2DO.unsafeDereference(),
         "unwrapping page1DO and page2DO outerizes both, yielding the same outer window");

      is(page1DO.executeInGlobal("me").return,
         "page 1", "page1DO continues to refer to original page");
      is(page2DO.executeInGlobal("me").return, "page 2",
         "page2DO refers to current page");

      is(page1DO.executeInGlobal("this === window").return, true,
         "page 1: Debugger.Object.prototype.executeInGlobal should outerize 'this'");
      is(page1DO.executeInGlobalWithBindings("this === window", {x: 2}).return, true,
         "page 1: Debugger.Object.prototype.executeInGlobal should outerize 'this'");

      is(page2DO.executeInGlobal("this === window").return, true,
         "page 2: Debugger.Object.prototype.executeInGlobal should outerize 'this'");
      is(page2DO.executeInGlobalWithBindings("this === window", {x: 2}).return, true,
         "page 2: Debugger.Object.prototype.executeInGlobal should outerize 'this'");

      // Debugger doesn't let one use outer windows as globals. You have to innerize.
      const outerDO = page1DO.makeDebuggeeValue(page1DO.unsafeDereference());
      ok(outerDO !== page1DO,
         "outer window gets its own D.O, distinct from page 1's global");
      ok(outerDO !== page2DO,
         "outer window gets its own D.O, distinct from page 2's global");
      SimpleTest.doesThrow(() => outerDO.executeInGlobal("me"),
                           "outer window D.Os can't be used as globals");

      SimpleTest.finish();
    };
  }
};
</script>
</pre>
</body>
</html>
