简体   繁体   中英

How to get iframe element button click javascript

i want to get the inner html contents of clicked element in iframe loaded content using javascript.

working jquery code

    var elems = document.getElementsByTagName('iframe');
    [].forEach.call(elems, function(el) {       
       $iframe = $(el.contentWindow.document);
       $iframe.find("body").click(function(e){
          console.log(e);   

       });
    });

You approach will not work. use the below method to communicate the click event.

In the Child Html ( which is inside the iframe )

$('body').on('click', function(){
    var type = 'bodyClick';
    var event = new CustomEvent('frameClick', { detail: type  })
    window.parent.document.dispatchEvent(event)
})

in Parent Html ( the html which has the iframe inserted )

$(document).ready(function(){
    window.document.addEventListener('frameClick', handleEvent, false)
    function handleEvent(e) {
      if(e.detail=="bodyClick") {
         //you can write your code here.
      }
    }
})

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