Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the functions wrapped in the $(document).ready(function(){}) of an iframe?

So I have an iframe that has some functions wrapped in a $(document).ready(function(){}) like this.

<script>
    $(document).ready(function(){
        function foo(){
            // do some stuff
        }
    });
</script>

I know that I can access the DOM with something like $('iframe').contents().find('something'), but can I access the foo() function from above?

like image 337
Dylan Hudson Avatar asked Oct 09 '22 20:10

Dylan Hudson


1 Answers

You cannot access the variables in that ready function of the iframe for the same reason that you cannot access local variables of any other function (you can't "go down" in scope). If you can modify the code in the iframe, however, you can always go up in scope. So in your iframe code:

$(document).ready(function() {
    function func1() {
        alert("Function in iframe");
    }

    parent.iframeFunctions = {
        test: func1
    }
});

The next problem is that you need to be able to access the function. You cannot use the normal jquery document ready, because the iframe is not finished loading when the parent page's DOM is ready and therefore your iframeFunctions object is still undefined in the parent page. You need this:

$(window).load(function() {
    iframeFunctions.test();
});

You can, however, access the global space of the iframe. Oh yeah, so far this is all assuming that the iframe source falls within the same domain policy. If not, there's a lot more work involved, and in a lot of cases it's not even worth it. The jquery object, for example, is in the global space, so here's how you get at the iframe's jquery:

$("iframe")[0].contentWindow.$("#divInIframe")

So, if you modified the content of the iframe source to use function expressions rather than function declartions:

var func1 = function() {
    alert("Function in iframe");
}

$(document).ready(function() {
    func1();
});

You'd be able to access it from the parent as well (after the window load event has fired):

$(window).load(function() {
    $("iframe")[0].contentWindow.func1();
});
like image 154
uɥƃnɐʌuop Avatar answered Oct 12 '22 09:10

uɥƃnɐʌuop