<!DOCTYPE HTML>
<html>
<head>
  <title>Bug 1280692 - navigator.sendBeacon() should send origin header</title>
  <!-- Including SimpleTest.js so we can use waitForExplicitFinish !-->
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
  <p id="display"></p>
  <div id="content" style="visibility: hidden">
    <iframe style="width:100%;" id="testframe"></iframe>
  </div>

<script class="testbody" type="text/javascript">

SimpleTest.waitForExplicitFinish();

const BEACON_URL = "http://example.com/tests/dom/tests/mochitest/beacon/beacon-originheader-handler.sjs";
// server returns any origin-header or 'no-header' if there is no header sent.
const ORIGIN_HEADER = "http://mochi.test:8888";

/* Description of the test:
 *   We call sendBeacon() cross origin and make sure that the
 *   origin header is actually set in the request.
 *
 * Since sendBeacon() does not expect any response, we are storing any
 * header on the server (*.sjs) and use an XMLHttpRequest to actually
 * retrieve the potentially set header back from the server. We assert
 * that the header is indeed *not* sent with the request. Since sendBeacon()
 * and also the XMLHttpRequest() are performed in an asynchronous fashion,
 * there is no guarantee that the sendBeacon() is actually executed before
 * the XMLHttpRequest().
 * Hence the xhr-response might be processed asynchronously.
 */

SpecialPowers.pushPrefEnv({'set': [["beacon.enabled", true]]}, runTest);

function queryHeaderFromServer() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "beacon-originheader-handler.sjs?queryheader", true);
  xhr.onload = function() {
    is(xhr.responseText, ORIGIN_HEADER, "SendBeacon should send origin header");
    SimpleTest.finish();
  };
  xhr.onerror = function() {
    ok(false, "xhr request returned error");
    SimpleTest.finish();
  };
  xhr.send();
}

function runTest() {
  // generate data and send beacon
  var formData = new FormData();
  formData.append('name', 'value');
  navigator.sendBeacon(BEACON_URL, formData);

  // start quering the result from the server
  queryHeaderFromServer();
}

</script>
</pre>
</body>
</html>
