繁体   English   中英

Iframe 点击事件仅在页面加载后工作一次 Javascript

[英]Iframe Click Event works Only Once after Page load Javascript

我正在尝试从 Iframe 获取用户点击事件。为此,我在下面编写了 Javascript 代码,问题是页面加载后只有第一次点击有效。 我需要在每次点击时触发它。 这该怎么做

 <script type="text/javascript">
 var clickIframe = window.setInterval(checkFocus, 100);
 var i = 0;

 function checkFocus() {
  if(document.activeElement == document.getElementById("pgl")) {
  console.log("clicked "+(i++));
  alert("i am clicked");
  window.focus();
  }
}  
</script>

这是 iframe

 <iframe src="https://www.neobux.com/" id="pgl" name="pgl" class="surfer_frame" frameborder="0" onmouseover="on_mouseover(this)" onmouseout="on_mouseout(this)">
</iframe>

这是您所拥有的工作版本。 (我怀疑来自这个答案。)

activeElement每秒查询一次,如果 iframe 处于活动状态,则会显示警报。

 // Initialize the counter. var checkCounter = 0; // Declare the function before assigning it as a callback. function checkFocus() { // Get the current minute and second as a timestamp. let timeStamp = new Date().toLocaleString("en-US", { minute: "2-digit", second: "2-digit" }); // Output the timestamp and currently active element to the results box. outputArea.value += "[" + timeStamp + "] Active element: " + document.activeElement + "\n"; // Try to alert if the iframe is active. try { if (document.activeElement == document.getElementById("pgl")) { outputArea.value += "\tiframe is active for check number " + ++checkCounter + ".\n"; // Prevent more than four alerts so the page isn't locked. if (checkCounter < 4) { outputArea.value += "\tAlerting.\n"; alert("I am clicked"); } else { outputArea.value += "\tNot alerting - more than 4 attempts.\n"; } } } catch (e) { // Show the error. outputArea.value += "\tUnable to alert. Error: " + e.substring(0, 20) + "...\n"; } // Scroll to the bottom of the results box. outputArea.scrollTop = outputArea.scrollHeight; } var outputArea = document.getElementById("output-area"); var clickFrame = window.setInterval(checkFocus, 1000);
 h1 { font-size: 16px; } code { color: darkgray; } #pgl, #output-area { width: 90%; height: 200px; }
 <body> <h1>Click the frame to trigger an alert:</h1> <iframe src="https://example.com" id="pgl"></iframe> <h1>Log of <code>clickFrame</code> activity:</h1> <textarea id="output-area"></textarea> </body>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM