<html>
<head>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/sw-test-pre.js"></script>
</head>
<body>
<script>
var scope = "/workers/service/serviceworkerclients-claim.https.html";
var activeWorker;

promise_test(async (test) => {
    var registration = await navigator.serviceWorker.getRegistration(scope);
    if (registration && registration.scope === scope)
        await registration.unregister();

    var registration = await navigator.serviceWorker.register("serviceworkerclients-claim-worker.js", { scope : scope });
    activeWorker = registration.active;
    if (activeWorker)
        return;
    activeWorker = registration.installing;
    return new Promise(resolve => {
        activeWorker.addEventListener('statechange', () => {
            if (activeWorker.state === "activated")
                resolve();
        });
    });
}, "Setup worker");

promise_test(async (test) => {
    var promise = new Promise((resolve, reject) => {
        navigator.serviceWorker.addEventListener("message", test.step_func((event) => {
            if (event.data === "CLAIMED") {
                resolve();
                return;
            }
            if (!event.data.startsWith("PASS")) {
                reject(event.data);
                return;
            }
        }));
    });

    activeWorker.postMessage("start");
    await promise;

    var response = await fetch("pinkelephant");
    var text = await response.text();
    assert_equals(text, "PASS");
}, "Test self.clients.claim");

var htmlString = '<html><script>async function doTest() { ' +
  '    var response = await fetch("https://127.0.0.1:8443/pinkelephant");' +
  '    var text = await response.text();' +
  '    window.parent.postMessage(text, "*");' +
  '}' +
  'doTest().catch(e => {' +
  '   window.parent.postMessage("Fetch failed", "*");'+
  '});' +
  '</scr' + 'ipt></h' + 'tml>';

promise_test(async (test) => {
    var promise = new Promise((resolve) => {
        window.addEventListener("message", (event) => resolve(event.data));
    });
    var frame = await withFrame("data:text/html," + htmlString);
    assert_equals(await promise, "Fetch failed");
}, "Test data URL frame");

promise_test(async (test) => {
    var blob = new Blob([''], {type: "text/html"});
    var blobURL = URL.createObjectURL(blob);
    var frame = await withFrame(blobURL);
    var response = await frame.contentWindow.fetch("https://127.0.0.1:8443/pinkelephant");
    var text = await response.text();
    assert_equals(text, "PASS");
}, "Test blob URL frame");

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