0

Is it possible to detect which element was clicked inside iframe?

var iframe = document.getElementById("my_iframe");
 iframe.document.addEventListener('click', function(event) {  
  console.log(this.id);
 }, false);
<iframe id="my_iframe"
        src="https://fr.wikipedia.org/wiki/Wiki"
        frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px"
         height="100%" width="100%">
</iframe>
  • Possible duplicate of [Detect Click into Iframe using JavaScript](https://stackoverflow.com/questions/2381336/detect-click-into-iframe-using-javascript) – SomeRSGuy Oct 19 '18 at 15:10

1 Answers1

1

You need to use .contentWindow.document on the iframe:

var iframe = document.getElementById("my_iframe");
iframe.contentWindow.document.addEventListener('click', function(event) {  
 console.log(this.id);
}, false);
<iframe id="my_iframe"
        src="https://fr.wikipedia.org/wiki/Wiki"
        frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px"
         height="100%" width="100%">
</iframe>

Mind you, you still need to deal with the pesky cross-origin issue. (You wont be able to see any elements, or access pretty much any content from within that iframe, if it's on a different origin than the site you're currently accessing).

If you have access to both sites though, you can communicate with the postmessage API: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Blue
  • 22,608
  • 7
  • 62
  • 92