Jack Cole
Jack Cole

Reputation: 1804

Executing a function on iframe load with greasemonkey

I am making a greasemonkey script for personal use, but I need it to execute a function when an iframe finishes loading. I tried having 2 seperate scripts, with one loading inside the iframe and executing the function, but the function is undefined since functions inside greasemonkey are in their own enviroment for security purposes.

Is there anyway to execute a function from inside an iframe that exists in greasemonkey in the parent?

Greasemonkey code for iframe parent:

frame2 = '[name="MainFrame"]';
function appendtoiframe2(){
    $(frame2).contentWindow.$('body').append('<div id="insecuremode_enable" style="position:fixed;bottom:0;background:#fff;">This div is now visible</div>');
});

Greasemonkey code for site inside iframe:

window.onload = function() {
    parent.appendtoiframe2();
}

Thank you.

Edit: I realized it might be silly doing it this way, instead of having the script just run in the site directly. But I only want this to execute if the site is in an iframe, which it's not always in. I am also trying to be able to control elements inside the parent from within the iframe.

Upvotes: 3

Views: 2807

Answers (1)

charlietfl
charlietfl

Reputation: 171669

You can bind an event handler to the iframe load . ( assumes same domain, otherwise no script access to iframe)

From main part of page:

$(function(){
     $('iframe[name="MainFrame"]').load(function(){
          $(this).contents().find('body').append('<div>.....</div>')
      });
});

API Reference: http://api.jquery.com/load-event/

Upvotes: 2

Related Questions