<!--
  Any copyright is dedicated to the Public Domain.
  http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>
<head>
  <title>Bug 1447871 - Test some service worker leak conditions</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="utils.js"></script>
  <script type="text/javascript" src="/tests/dom/events/test/event_leak_utils.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display"></p>
<script class="testbody" type="text/javascript">

const scope = new URL("empty.html?leak_tests", location).href;
const script = new URL("empty.js", location).href;

// Manipulate service worker DOM objects in the frame's context.
// Its important here that we create a listener callback from
// the DOM objects back to the frame's global in order to
// exercise the leak condition.
async function useServiceWorker(contentWindow) {
  contentWindow.navigator.serviceWorker.oncontrollerchange = _ => {
    contentWindow.controlledChangeCount += 1;
  };
  let reg = await contentWindow.navigator.serviceWorker.getRegistration(scope);
  reg.onupdatefound = _ => {
    contentWindow.updateCount += 1;
  };
  reg.active.onstatechange = _ => {
    contentWindow.stateChangeCount += 1;
  };
}

async function runTest() {
  await SpecialPowers.pushPrefEnv({"set": [
    ["dom.serviceWorkers.exemptFromPerDomainMax", true],
    ["dom.serviceWorkers.enabled", true],
    ["dom.serviceWorkers.testing.enabled", true]
  ]});

  let reg = await navigator.serviceWorker.register(script, { scope });
  await waitForState(reg.installing, "activated");

  try {
    await checkForEventListenerLeaks("ServiceWorker", useServiceWorker);
  } catch (e) {
    ok(false, e);
  } finally {
    await reg.unregister();
    SimpleTest.finish();
  }
}

SimpleTest.waitForExplicitFinish();
addEventListener("load", runTest, { once: true });
</script>
</pre>
</body>
</html>
