简体   繁体   中英

How to detect which element was clicked inside iframe javascript

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> 

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

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