Waclock
Waclock

Reputation: 1716

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.

Upvotes: 3

Views: 1057

Answers (1)

Onur Yıldırım
Onur Yıldırım

Reputation: 33634

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.

Upvotes: 7

Related Questions