简体   繁体   中英

Detect a button inside of an iframe being clicked

I'm trying to detect a button click inside of an 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. 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. 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. 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.

The way to approach this is with an event listener. Like so:

Note: add an id called "myFrame" to your iframe.

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 .

The purpose of setInterval is to run a specific code once every x milliseconds. JS is sophisticated enough to give you all the API to handle everything you will ever need. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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