<!DOCTYPE html>
<html>
<head>
    <meta name="referrer" content="unsafe-url">
    <script src="/js-test-resources/js-test.js"></script>
    <script src="/cookies/resources/cookie-utilities.js"></script>
    <script src="resources/util.js"></script>
</head>
<body onload="setTimeout('runTest()', 0)">
<script>
    description("Check that document.referrer is downgraded to the eTLD+1 after a cross-site navigation with link query.");
    jsTestIsAsync = true;

    let numberOfTries = 0;
    function testReferrer() {
        if (document.referrer === prevalentResourceOrigin + "/") {
            testPassed("The referrer is downgraded.");
            setEnableFeature(false, finishJSTest);
        } else if (++numberOfTries <= 5)
            setTimeout(testReferrer, 200);
        else {
            testFailed("The referrer is not downgraded: " + document.referrer);
            setEnableFeature(false, finishJSTest);
        }
    }

    function navigateSameOriginToAddQuery() {
        document.location.href = prevalentResourceOrigin + "/resourceLoadStatistics/downgraded-referrer-for-navigation-with-link-query-from-prevalent-resource.html?link=query";
    }

    function navigateCrossOrigin() {
        document.location.href = destinationOrigin + "/resourceLoadStatistics/downgraded-referrer-for-navigation-with-link-query-from-prevalent-resource.html";
    }

    const destinationOrigin = "http://localhost:8000";
    const prevalentResourceOrigin = "http://127.0.0.1:8000";
    function runTest() {
        if (document.location.origin === prevalentResourceOrigin && document.location.search === "") {
            navigateSameOriginToAddQuery();
        } else if (document.location.origin === prevalentResourceOrigin) {
            setEnableFeature(true, function () {
                testRunner.setStatisticsPrevalentResource(prevalentResourceOrigin, true, function() {
                    if (!testRunner.isStatisticsPrevalentResource(prevalentResourceOrigin))
                        testFailed("Host did not get set as prevalent resource.");
                    testRunner.statisticsUpdateCookieBlocking(navigateCrossOrigin);
                });
            });
        } else {
            testReferrer();
        }
    }
</script>
</body>
</html>
