<!DOCTYPE html>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=1091883
-->
<head>
  <meta charset="utf-8">
  <meta name="referrer" content="origin-when-cross-origin">
  <title>Test for Bug 1091883</title>
  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<p><a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1091883">Mozilla Bug 1091883</a></p>
<h2>Results</h2>
<pre id="results">Running...</pre>

<script>
SimpleTest.waitForExplicitFinish();

var origins = [
  "http://mochi.test:8888", "http://example.com", "http://example.org"];
var numOrigins = origins.length;

// For each combination of (frame, subframe, target) origins, this test
// includes a "frame" that includes a "subframe"; and then this test
// navigates this "subframe" to the "target".  Both the referrer and
// the triggering principal are this test, i.e., "http://mochi.test:8888".
// Since the referrer policy is origin-when-cross-origin, we expect to have
// a full referrer if and only if the target is also "http://mochi.test:8888";
// in all other cases, the referrer needs to be the origin alone.
var numTests = numOrigins * numOrigins * numOrigins;

// Helpers to look up the approriate origins for a given test number.
function getFrameOrigin(i) {
  return origins[(i / (numOrigins * numOrigins)) | 0];
}
function getSubframeOrigin(i) {
  return origins[((i / numOrigins) | 0) % 3];
}
function getTargetOrigin(i) {
  return origins[i % 3];
}

// Create the frames, and tell them which subframes to load.
for (var i = 0; i < numTests; i++) {
  var frame = document.createElement("iframe");
  frame.src = getFrameOrigin(i) +
              "/tests/dom/base/test/file_bug1091883_frame.html#" +
              getSubframeOrigin(i);
  document.body.appendChild(frame);
}

// Navigate all subframes to the target.
window.onload = function() {
  for (var i = 0; i < numTests; i++) {
    frames[i].frames[0].location = getTargetOrigin(i) +
        "/tests/dom/base/test/file_bug1091883_target.html#" + i;
  }
};

// Check referrer messages from the target.
var results = {};
function makeResultsKey(i) {
  return i + ": " + getFrameOrigin(i) + " | " + getSubframeOrigin(i) + " -> " +
         getTargetOrigin(i);
}
window.addEventListener("message", function(event) {
  var out = event.data.split(" ");
  var referrer = out[0];
  var testRun = +out[1];
  results[makeResultsKey(testRun)] = referrer;
  if (event.origin == "http://mochi.test:8888") {
    is(referrer,
       "http://mochi.test:8888/tests/dom/base/test/test_bug1091883.html",
       "must be full referrer");
  } else {
    is(referrer, "http://mochi.test:8888/", "must be origin referrer");
  }
  if (Object.keys(results).length == numTests) {
    document.getElementById("results").textContent =
        JSON.stringify(results, null, 4);
    SimpleTest.finish();
  }
});
</script>

</body>
</html>