Invoking JavaScript code in an iframe from the parent page

后端 未结 17 1791
栀梦
栀梦 2020-11-21 07:00

Basically, I have an iframe embedded in a page and the iframe has some JavaScript routines I need to invoke from the parent page.

Now the o

17条回答
  •  迷失自我
    2020-11-21 07:02

    I found quite an elegant solution.

    As you said, it's fairly easy to execute code located on the parent document. And that's the base of my code, do to just the opposite.

    When my iframe loads, I call a function located on the parent document, passing as an argument a reference to a local function, located in the iframe's document. The parent document now has a direct access to the iframe's function thru this reference.

    Example:

    On the parent:

    function tunnel(fn) {
        fn();
    }
    

    On the iframe:

    var myFunction = function() {
        alert("This work!");
    }
    
    parent.tunnel(myFunction);
    

    When the iframe loads, it will call parent.tunnel(YourFunctionReference), which will execute the function received in parameter.

    That simple, without having to deal with the all the non-standards methods from the various browsers.

提交回复
热议问题