Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering Javascript inside dynamically created iframe

I'm currently building a chrome extension, in which I've managed to make a pop-up using an Iframe, whenever a user click on a button of my chrome extension.

Inside of my iFrame I'm loading 2 .js files: jQuery and "modal.js" from the chrome extension. Doing an inspect I can see that the file is loaded (modal.js), however I'm using the following code, which is not triggered:

  $('#frameID').ready(function(){
    $('#sbm-new-group').click(function(){
      console.log("hello");
     });
  });

This is not working, and even if I try using $(document).ready, nothing fires up. I'd like to know if there's anyway in triggering the method using the javascript inside the iFrame.

Any help is greately appreciated.

like image 439
Waclock Avatar asked May 03 '26 01:05

Waclock


1 Answers

You should access the iframe's document to bind the .ready() handler.
Here is a demo fiddle.

Note: This is possible if you're on the same domain.

var iframe = document.getElementById('frameID'),
    iframeWin = iframe.contentWindow || iframe,
    iframeDoc = iframe.contentDocument || iframeWin.document;

$(iframeDoc).ready(function (event) {
    alert('iframe ready');
    // now you can access any element in the iframe (if same domain)
    $(iframeDoc).find('#sbm-new-group').on('click', function (event) {
         alert('clicked');
    });
});

[Edit] Extra Notes:

  • To call a function in the owner global scope, from the iframe document:

    parent.someMethod();

  • To call a function in the iframe global scope, from the owner document:

    iframeWin.someMethod();

  • To execute scripts within the iframe, from the owner document:

// this is called from the iframe
window.hello = function () {
    alert('hello from owner!');
};

// we'll write some scripts within the iframe that will be executed immediately
iframeDoc.open();
iframeDoc.write('\<script>alert("hello from iframe!");\<\/script>');
iframeDoc.write('\<script>parent.hello();\<\/script>');
iframeDoc.close();

Here is another fiddle demonstrating this one.

like image 108
Onur Yıldırım Avatar answered May 05 '26 13:05

Onur Yıldırım



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!