<!DOCTYPE html>
<html>
<body onload="runTest()">
<script src="/js-test-resources/js-test.js"></script>
<script src="/js-test-resources/ui-helper.js"></script>
<script src="/resourceLoadStatistics/resources/util.js"></script>
<script>
    description("Tests that top frame storage access is always granted in case the page requests it.");
    jsTestIsAsync = true;

    function activateElement(elementId) {
        var element = document.getElementById(elementId);
        var centerX = element.offsetLeft + element.offsetWidth / 2;
        var centerY = element.offsetTop + element.offsetHeight / 2;
        UIHelper.activateAt(centerX, centerY).then(
            function () {
            },
            function () {
                testFailed("Promise rejected.");
                setEnableFeature(false, finishJSTest);
            }
        );
    }

    var hasStorageAccess;
    var requestStorageAccessResolved;

    function makeRequestWithUserGesture() {
        setEnableFeature(true, function() {
            var promise = document.requestStorageAccess();
            promise.then(
                function () {
                    requestStorageAccessResolved = true;
                    continueAfterRequestWithUserGesture();
                },
                function () {
                    requestStorageAccessResolved = false;
                    continueAfterRequestWithUserGesture();
                }
            );
        });
    }

    function continueAfterRequestWithUserGesture() {
        var promise = document.hasStorageAccess();
        promise.then(
            function (hasAccess) {
                hasStorageAccess = hasAccess;
                shouldBe("requestStorageAccessResolved", "true");
                shouldBe("hasStorageAccess", "true");
                setEnableFeature(false, finishJSTest);
            },
            function (reason) {
                testFailed("document.hasStorageAccess() was rejected. Reason: " + reason);
                setEnableFeature(false, finishJSTest);
            }
        );
    }

    function runTest() {
        activateElement("theButton");
    }
</script>
<button id="theButton" onclick="makeRequestWithUserGesture()">Request Access</button>
</body>
</html>
