<html>
<head>
<script>

function init() {
  let targetURL = new URL(window.location.href);
  let i = targetURL.pathname.lastIndexOf("/");
  targetURL.pathname = `${targetURL.pathname.substring(0, i)}/target.html`;

  window.addEventListener("TabPaint:FinalResults", (event) => {
    let { fromParent, fromContent } = event.detail;

    tpRecordTime([fromParent, fromContent].join(","), 0, "tabpaint-from-parent, tabpaint-from-content");
  }, {once: true});

  window.addEventListener("TabPaint:OpenFromContent", (event) => {
    let target = document.getElementById("target");

    //win.performance.now() + win.performance.timing.navigationStart gives the UNIX timestamp.
    let now = window.performance.now() + window.performance.timing.navigationStart;

    target.href = `${targetURL.href}?${now}`;
    target.click();
  });

  async function tryPing() {
    let pingPromise = new Promise(resolve => {
      window.addEventListener("TabPaint:Pong", resolve, {once: true});
      dispatchEvent(new CustomEvent("TabPaint:Ping", {bubbles: true}));
    });
    let timeoutPromise = new Promise((resolve, reject) => setTimeout(reject, 500));

    try {
      await Promise.race([pingPromise, timeoutPromise]);
    } catch (e) {
      return tryPing();
    }
    return null;
  }

  tryPing().then(() => {
    dispatchEvent(new CustomEvent("TabPaint:Go", {
      bubbles: true,
      detail: {
        target: targetURL.href,
      },
    }));
  });
}
</script>
</head>
<body onload="init();">
  Hello, Talos!

  <a href="#" id="target" target="_blank">I'll open a new tab</a>
</body>
</html>
