简体   繁体   English

检测 iframe 内部的按钮被点击

[英]Detect a button inside of an iframe being clicked

I'm trying to detect a button click inside of an iframe.我正在尝试检测 iframe 内部的按钮点击。 I've currently worked out how to make it alert me when I click inside the iframe but now need to extend that to button inside of an iframe.我目前已经研究了如何在我单击 iframe 内部时让它提醒我,但现在需要将其扩展到 iframe 内部的按钮。 If I need to completely recreate the code to make it more effeicient, I am ok with that.如果我需要完全重新创建代码以使其更高效,我可以接受。

var monitor = setInterval(function(){
  var elem = document.activeElement;
  if(elem && elem.tagName == 'IFRAME'){
  alert('Clicked');
  clearInterval(monitor);
  }
  
}, 100);

I am not sure why you're using a setInterval.我不确定你为什么使用 setInterval。 In an odd way, you simulate the javascript event listener in the sense that for every 100 milliseconds you check if the currently active element is the IFRAME.以一种奇怪的方式,您模拟了 javascript 事件侦听器,每 100 毫秒您检查当前活动的元素是否是 IFRAME。 After you clicked on it, it will show the alert but if you focus on another element and then come back to the IFRAME, it will not show the alert again.单击它后,它将显示警报,但如果您关注另一个元素然后返回 IFRAME,它将不会再次显示警报。

The way to approach this is with an event listener.解决此问题的方法是使用事件侦听器。 Like so:像这样:

Note: add an id called "myFrame" to your iframe.注意:在 iframe 中添加一个名为“myFrame”的 ID。

const element = document.getElementsById('myFrame');
element.addEventListener("click", myFunction);

function myFunction() {
  alert('Clicked');
}

You should use the exact same approach for the button as well, only you will get the button in the getElementById .您也应该对按钮使用完全相同的方法,只有您会在getElementById中获得按钮。

The purpose of setInterval is to run a specific code once every x milliseconds. setInterval 的目的是每 x 毫秒运行一次特定代码。 JS is sophisticated enough to give you all the API to handle everything you will ever need. JS 足够复杂,可以为您提供所有 API 来处理您将需要的一切。 More often than not you will use setInterval just for fancy algorithms that you may implement, but usually, for building normal websites you'll rarely need it.通常,您只会将 setInterval 用于您可能实现的奇特算法,但通常,对于构建普通网站,您很少需要它。

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

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