<!-- webkit-test-runner [ UsesBackForwardCache=true ] -->
<!DOCTYPE html>
<html>
<body>
<script src="../../resources/js-test-pre.js"></script>
<script>
description('Tests that a page that has a MessagePort with a pending message can enter PageCache.');
window.jsTestIsAsync = true;

let afterPageCacheRestore = false;

window.addEventListener("pageshow", function(event) {
    debug("pageshow - " + (event.persisted ? "" : "not ") + "from cache");

    if (event.persisted) {
        testPassed("Page did enter and was restored from the page cache");
        afterPageCacheRestore = true;
    }
}, false);

window.addEventListener("pagehide", function(event) {
    debug("pagehide - " + (event.persisted ? "" : "not ") + "entering cache");
    if (!event.persisted) {
        testFailed("Page did not enter the page cache.");
        finishJSTest();
    }
    port2.postMessage("foo");
}, false);

window.addEventListener('load', function() {
    channel = new MessageChannel();
    port1 = channel.port1;
    port1.onmessage = (_e) => {
        e = _e;
        shouldBeEqualToString("e.data", "foo");
        shouldBeTrue("afterPageCacheRestore");
        finishJSTest();
    };
    port2 = channel.port2;

    // This needs to happen outside the onload handler so that a history
    // item is created.
    setTimeout(function() {
        // Force a back navigation back to this page.
        window.location = "resources/page-cache-helper.html";
    }, 0);
}, false);

</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html>
