Calling a parent window function from an iframe

后端 未结 10 2374
悲&欢浪女
悲&欢浪女 2020-11-22 01:43

I want to call a parent window JavaScript function from an iframe.



&         


        
10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 02:30

    While some of these solutions may work, none of them follow best practices. Many assign global variables and you may find yourself making calls to multiple parent variables or functions, leading to a cluttered, vulnerable namespace.

    To avoid this, use a module pattern. In the parent window:

    var myThing = {
        var i = 0;
        myFunction : function () {
            // do something
        }
    };
    
    var newThing = Object.create(myThing);
    

    Then, in the iframe:

    function myIframeFunction () {
        parent.myThing.myFunction();
        alert(parent.myThing.i);
    };
    

    This is similar to patterns described in the Inheritance chapter of Crockford's seminal text, "Javascript: The Good Parts." You can also learn more at w3's page for Javascript's best practices. https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals

提交回复
热议问题