Search code examples
javascripthtmliframeonclickonclicklistener

Listen click text in dynamically created iframe


I want to add event when click on text in iframe. This iframe created after the document has loaded. After created, there is document object #document created in iframe element. In this code, the click on text in iframe could not be catched.

<html>
<head>
    <script src="../ext/plugins/jquery/dist/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            //add iframe
            var iframe = document.createElement('iframe');
            var html = '<body>Foo</body>';
            iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
            $('#iframe-holder').append(iframe);
        })
        $(document).on('click','#iframe-holder > iframe',function(){
            console.log('you have clicked text in iframe');
            //do something
        });
    </script>
</head>
<body>
    <div id="iframe-holder">
        
    </div>
</body>

Solution

  • I have tested both @Teemu and @Tanay answer . It works when I added in document.addEventListener('load',function(event){//sucessfully fired when added here}) Then, I have change iframe.src to source document, page1.html.

    <html>
    <head>
        <script src="../ext/plugins/jquery/dist/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                //add iframe
                var iframe = document.createElement('iframe');
                var html = '<body>Foo</body>';
                //iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
                iframe.src = 'page1.html';
                $('#iframe-holder').append(iframe);
            })
    
    document.addEventListener(
    'load',
    function(event){
      //1:
      $($('#iframe-holder > iframe')[0].contentDocument).on('click', function (e) {
      console.log('ln34');
        });
      //2:    
      const iframe = document.querySelector('#iframe-holder > iframe');
        iframe.onload = function() {
            const iframeDocument = iframe.contentWindow.document;
            iframeDocument.addEventListener('click', function(e) {
                console.log('ln43');
            })
        }
    },
    true // Capture event
    );
    
        </script>
    </head>
    <body>
        <div id="iframe-holder">
            
        </div>
    </body>
    

    Thank you for help.