Calling a parent window function from an iframe

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

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



&         


        
相关标签:
10条回答
  • 2020-11-22 02:31

    The solution given by Ash Clarke for subdomains works great, but please note that you need to include the document.domain = "mydomain.com"; in both the head of the iframe page and the head of the parent page, as stated in the link same origin policy checks

    An important extension to the same origin policy implemented for JavaScript DOM access (but not for most of the other flavors of same-origin checks) is that two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name. For example, if http://en.example.com/ and http://fr.example.com/ both set document.domain to "example.com", they would be from that point on considered same-origin for the purpose of DOM manipulation.

    0 讨论(0)
  • 2020-11-22 02:34

    I have posted this as a separate answer as it is unrelated to my existing answer.

    This issue recently cropped up again for accessing a parent from an iframe referencing a subdomain and the existing fixes did not work.

    This time the answer was to modify the document.domain of the parent page and the iframe to be the same. This will fool the same origin policy checks into thinking they co-exist on exactly the same domain (subdomains are considered a different host and fail the same origin policy check).

    Insert the following to the <head> of the page in the iframe to match the parent domain (adjust for your doctype).

    <script>
        document.domain = "mydomain.com";
    </script>
    

    Please note that this will throw an error on localhost development, so use a check like the following to avoid the error:

    if (!window.location.href.match(/localhost/gi)) {
        document.domain = "mydomain.com";
    } 
    
    0 讨论(0)
  • 2020-11-22 02:36

    parent.abc() will only work on same domain due to security purposes. i tried this workaround and mine worked perfectly.

    <head>
        <script>
        function abc() {
            alert("sss");
        }
    
        // window of the iframe
        var innerWindow = document.getElementById('myFrame').contentWindow;
        innerWindow.abc= abc;
    
        </script>
    </head>
    <body>
        <iframe id="myFrame">
            <a onclick="abc();" href="#">Click Me</a>
        </iframe>
    </body>
    

    Hope this helps. :)

    0 讨论(0)
  • 2020-11-22 02:36

    With Firefox and Chrome you can use :

    <a href="whatever" target="_parent" onclick="myfunction()">
    

    If myfunction is present both in iframe and in parent, the parent one will be called.

    0 讨论(0)
提交回复
热议问题