JSFiddle - React, Tailwind, and code Playground

by velo_ninja

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Send Message to Iframe</title>
</head>
<body>

<script>

	function startCounting() {let count = 0;
  	
    function incrementAndLog() {
    	count++; console.log("Count:", count);
      xxx(count);
    }
    // Set an interval to call the incrementAndLog function every 3 seconds
    const intervalId = setInterval(incrementAndLog, 3000);
    // Optionally, you can return the intervalId if you want to clear the interval later
    return intervalId;
  }
	
    // To stop counting, you can use clearInterval with the returned intervalId
    // Uncomment the line below if you want to stop the counting after a certain time (e.g., 10 seconds)
    // setTimeout(() => clearInterval(countingIntervalId), 10000);






  var iframes;

  setTimeout(function() {
    iframes = document.querySelectorAll("iframe");
    console.log(iframes);
    
    if (iframes.length > 0) {
      // Set 'id' attribute for the first iframe
      iframes[0].setAttribute("id", "html1");

      var iframeId = iframes[0].getAttribute("id");
      console.log("Iframe ID:", iframeId);

      // Set 'allow' attribute and other operations...

      //setTimeout(function() {
      //  const countingIntervalId = startCounting(); 
      //}, 3000);
    }
  }, 3000);

  function xxx(countingIntervalId) {console.log(countingIntervalId);
    if (iframes && iframes.length > 0) {
      // Accessing the contentWindow of the first iframe by its 'id'
      var iframeContentWindow = document.getElementById("html1").contentWindow;

      // Sending a simple string message to the iframe
      //iframeContentWindow.postMessage("Hello, iframe!", "https://example.com");
      iframeContentWindow.postMessage(countingIntervalId, "*");
    }
  }
</script>

</body>
</html>