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

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

/* eslint-disable mozilla/balanced-listeners */

add_task(async function test_postMessage() {
  let extensionData = {
    manifest: {
      content_scripts: [
        {
          "matches": ["http://mochi.test/*/file_sample.html"],
          "js": ["content_script.js"],
          "run_at": "document_start",
          "all_frames": true,
        },
      ],

      web_accessible_resources: ["iframe.html"],
    },

    background() {
      browser.test.sendMessage("iframe-url", browser.runtime.getURL("iframe.html"));
    },

    files: {
      "content_script.js": function() {
        window.addEventListener("message", event => {
          if (event.data == "ping") {
            event.source.postMessage({pong: location.href},
                                     event.origin);
          }
        });
      },

      "iframe.html": `<!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <script src="content_script.js"><\/script>
          </head>
        </html>`,
    },
  };

  let createIframe = url => {
    let iframe = document.createElement("iframe");
    return new Promise(resolve => {
      iframe.src = url;
      iframe.onload = resolve;
      document.body.appendChild(iframe);
    }).then(() => {
      return iframe;
    });
  };

  let awaitMessage = () => {
    return new Promise(resolve => {
      let listener = event => {
        if (event.data.pong) {
          window.removeEventListener("message", listener);
          resolve(event.data);
        }
      };
      window.addEventListener("message", listener);
    });
  };

  let extension = ExtensionTestUtils.loadExtension(extensionData);
  await extension.startup();

  let iframeURL = await extension.awaitMessage("iframe-url");
  let testURL = SimpleTest.getTestFileURL("file_sample.html");

  for (let url of [iframeURL, testURL]) {
    info(`Testing URL ${url}`);

    let iframe = await createIframe(url);

    iframe.contentWindow.postMessage(
      "ping", url);

    let pong = await awaitMessage();
    is(pong.pong, url, "Got expected pong");

    iframe.remove();
  }

  await extension.unload();
});
</script>

</body>
</html>
