<!doctype html>
<html>
<head>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/utils.js"></script>
<script src="resources/routines.js"></script>
</head>
<body>
<script>
var activeWorker;
var uuid = token();
var url = "/WebKit/service-workers/resources/service-worker-iframe-preload-script.py?token=" + uuid;
var frame;
const channel = new MessageChannel();

function waitUntilActivating()
{
    return new Promise(resolve => {
        channel.port2.onmessage = (event) => {
            if (event.data === "activating")
                resolve();
        };
    });
}

function triggerActivation()
{
    activeWorker.postMessage("activate");
}

promise_test(async (test) => {
    if (window.testRunner) {
        testRunner.setUseSeparateServiceWorkerProcess(true);
        await fetch("").then(() => { }, () => { });
    }

    let registration = await navigator.serviceWorker.register("/WebKit/service-workers/service-worker-iframe-preload-worker.js", { scope : url });
    if (!registration.installing) {
        registration.unregister();
        registration = await navigator.serviceWorker.register("/WebKit/service-workers/service-worker-iframe-preload-worker.js", { scope : url });
    }
    activeWorker = registration.installing;
    activeWorker.postMessage({ port: channel.port1 }, [channel.port1]);

    await waitUntilActivating();
    if (registration.navigationPreload)
        await registration.navigationPreload.enable();
}, "Setup activating worker");

promise_test(async (test) => {
    // Set value to 'before-navigation'
    await fetch(url + "&value=before-navigation", { method: 'POST' });

    // Start loading iframe, with activating worker, so only preload will start.
    const iframePromise = withIframe(url);

    // Wait a little bit to do a fetch. This fetch should happen after the fetch event, which is pending.
    // It should receive 'before-navigation'
    await new Promise(resolve => setTimeout(resolve, 100));
    const fetchPromise = fetch(url);

    // Trigger fetch, which will trigger the preload response.
    activeWorker.postMessage("fetch");

    const response = await fetchPromise;
    assert_equals(await response.text(), "nothing");

    const frame = await iframePromise;
    assert_equals(frame.contentWindow.document.body.innerText, "before-navigation");
}, "Service worker load uses preload that starts as soon as possible");
</script>
</body>
</html>
