<!DOCTYPE html>
<head>
<meta charset="utf8">
<script>
function waitForCondition(aCond, aCallback, aErrorMsg) {
    var tries = 0;
    var interval = setInterval(() => {
      if (tries >= 30) {
        result.push({
          'error': `Exceeded 30 tries waiting for animation`
        })
        clearInterval(interval);
        parent.postMessage(result, "*");
        return;
      }

      var conditionPassed;
      try {
        conditionPassed = aCond();
      } catch (e) {
        result.push({
          'error': `${e}\n${e.stack}`
        })
        clearInterval(interval);
        parent.postMessage(result, "*")
        return;
      }

      if (conditionPassed) {
        clearInterval(interval);
        aCallback();
      }

      tries++;
    }, 100);
  }

window.onload = async () => {
  parent.postMessage("ready", "*");
}

var result = [];

window.addEventListener("message", async function listener(event) {
  if (event.data[0] == "gimme") {

    const testDiv = document.getElementById("testDiv");
    const animation = testDiv.animate({ opacity: [0, 1] }, 100000);
    animation.play();

    waitForCondition(
      () => animation.currentTime > 100,
        () => {

          result.push({
            'name': 'animation.startTime',
            'value': animation.startTime
          });
          result.push({
            'name': 'animation.currentTime',
            'value': animation.currentTime
          });
          result.push({
            'name': 'animation.timeline.currentTime',
            'value': animation.timeline.currentTime
          });

          if (document.timeline) {
            result.push({
              'name': 'document.timeline.currentTime',
              'value': document.timeline.currentTime
            });
          }

          parent.postMessage(result, "*")
        },
        "animation failed to start");
  }
});
</script>
</head>
<body>
<div id="testDiv">test</div>
</body>
</html>
