<!DOCTYPE html>
<meta charset="utf-8" />
<title>PaymentRequest show() rejects if doc is not fully active</title>
<link rel="help" href="https://w3c.github.io/payment-request/#show-method" />
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<body>
<script>
const applePay = Object.freeze({
  supportedMethods: "https://apple.com/apple-pay",
  data: {
    version: 3,
    merchantIdentifier: "merchant.com.example",
    countryCode: "US",
    merchantCapabilities: ["supports3DS"],
    supportedNetworks: ["visa"],
  },
});
const validMethod = Object.freeze({
  supportedMethods: "basic-card",
});
const validMethods = Object.freeze([validMethod, applePay]);
const validAmount = Object.freeze({
  currency: "USD",
  value: "5.00",
});
const validTotal = Object.freeze({
  label: "Total due",
  amount: validAmount,
});
const validDetails = Object.freeze({
  total: validTotal,
});

async function getLoadedPaymentRequest(iframe, url) {
  await new Promise((resolve) => {
    iframe.addEventListener("load", resolve, { once: true });
    iframe.src = url;
  });
  const { PaymentRequest } = iframe.contentWindow;
  const request = new PaymentRequest(validMethods, validDetails);
  return request;
}

promise_test(async (t) => {
  const iframe = document.createElement("iframe");
  document.body.appendChild(iframe);
  // Make a request in the iframe.
  const request = await getLoadedPaymentRequest(
    iframe,
    "resources/page1.html"
  );
  await test_driver.bless("show payment request");
  const showPromise = request.show();
  const firstCtor = iframe.contentWindow.DOMException;

  // Navigate the iframe to a new location. Wait for the load event to fire.
  const request2 = await getLoadedPaymentRequest(
    iframe,
    "resources/page2.html"
  );

  await promise_rejects_dom(
    t,
    "AbortError",
    firstCtor,
    showPromise,
    "Show promise should abort."
  );

  // The navigation dismisses the previous payment request so it
  // now possible to show another one.
  await test_driver.bless("show 2nd payment request");
  const showPromise2 = request2.show();
  const secondCtor = iframe.contentWindow.DOMException;
  // no longer fully active
  iframe.remove();
  await promise_rejects_dom(
    t,
    "AbortError",
    secondCtor,
    showPromise2,
    "Show promise should abort."
  );
}, "If a payment request is showing, but its document is navigated away (so no longer fully active), the payment sheet is dismissed.");
</script>
</body>
