<!DOCTYPE html>
<meta charset=utf-8>
<meta name="timeout" content="long">
<title>Web Locks API: bfcache</title>
<link rel=help href="https://w3c.github.io/web-locks/">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/utils.js"></script>
<script src="/common/dispatcher/dispatcher.js"></script>
<script src="/html/browsers/browsing-the-web/back-forward-cache/resources/helper.sub.js"></script>
<script>
  const connectToSharedWorker = async () => {
    await window.pageShowPromise;
    window.worker = new SharedWorker("/web-locks/resources/worker.js");
    worker.port.start();
  }
  function double_docs_test(func, description) {
    promise_test(async t => {
      const pageA1 = new RemoteContext(token());
      const pageA2 = new RemoteContext(token());
      const pageB1 = new RemoteContext(token());
      const pageB2 = new RemoteContext(token());

      const urlA1 = executorPath + pageA1.context_id;
      const urlA2 = executorPath + pageA2.context_id;
      const urlB1 = originCrossSite + executorPath + pageB1.context_id;
      const urlB2 = originCrossSite + executorPath + pageB2.context_id;

      window.open(urlA1, "_blank", "noopener");
      window.open(urlA2, "_blank", "noopener");

      await func(pageA1, pageA2);

      await Promise.all([
        navigateAndThenBack(pageA1, pageB1, urlB1),
        navigateAndThenBack(pageA2, pageB2, urlB2),
      ]);

      await assert_not_bfcached(pageA1);
      await assert_not_bfcached(pageA2);
    }, description);
  }

  double_docs_test(async (pageA1, pageA2) => {
    await Promise.all([
      pageA1.execute_script(connectToSharedWorker),
      pageA2.execute_script(connectToSharedWorker),
    ]);
    await pageA1.execute_script(async () => {
      const script = document.createElement("script");
      script.src = "/web-locks/resources/helpers.js";
      document.head.append(script);
      await new Promise(resolve => script.onload = resolve);
      await postToWorkerAndWait(worker.port, { op: "request", name: uniqueNameByQuery() });
    });
  }, "A new held lock must prevent bfcache on all connected documents");

  double_docs_test(async (pageA1, pageA2) => {
    await pageA1.execute_script(connectToSharedWorker);
    await pageA1.execute_script(async () => {
      const script = document.createElement("script");
      script.src = "/web-locks/resources/helpers.js";
      document.head.append(script);
      await new Promise(resolve => script.onload = resolve);
      await postToWorkerAndWait(worker.port, { op: "request", name: uniqueNameByQuery() });
    });
    await pageA2.execute_script(connectToSharedWorker);
  }, "An existing held lock must prevent bfcache on all connected documents");
</script>
