<!DOCTYPE HTML>
<html>
<head>
  <title>Test for SpecialPowers.spawn</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>

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

<span id="hello">World.</span>

<script>
/* globals SpecialPowers, content */

  add_task(async function() {
    let frame = document.getElementById("iframe");
    frame.src = "https://example.com/tests/testing/mochitest/tests/Harness_sanity/file_spawn.html";

    await new Promise(resolve => {
      frame.addEventListener("load", resolve, {once: true});
    });

    let result = await SpecialPowers.spawn(frame, ["#span"], selector => {
      let elem = content.document.querySelector(selector);
      return elem.textContent;
    });

    is(result, "Hello there.", "Got correct element text from frame");

    /* eslint-disable no-shadow */
    result = await SpecialPowers.spawn(frame, ["#hello"], selector => {
      return SpecialPowers.spawn(content.parent, [selector], selector => {
        let elem = content.document.querySelector(selector);
        return elem.textContent;
      });
    });

    is(result, "World.", "Got correct element text from frame's window.parent");

    result = await SpecialPowers.spawn(frame.contentWindow, ["#span"], selector => {
      let elem = content.document.querySelector(selector);
      return elem.textContent;
    });

    is(result, "Hello there.", "Got correct element text from window proxy");

    result = await SpecialPowers.spawn(SpecialPowers.getPrivilegedProps(frame, "browsingContext"),
                                       ["#span"], selector => {
      let elem = content.document.querySelector(selector);
      return elem.textContent;
    });

    is(result, "Hello there.", "Got correct element text from browsing context");

    let line = 58; // Keep this in sync with the line number where the callback function starts.
    let callback = () => {
      let e = new Error("Hello.");
      return { filename: e.fileName, lineNumber: e.lineNumber };
    };

    let loc = await SpecialPowers.spawn(frame, [], callback);
    is(loc.filename, location.href, "Error should have correct script filename");
    is(loc.lineNumber, line + 2, "Error should have correct script line number");
  });
</script>
</body>
</html>