parent-child interaction iframe page

The following parent page and sub-page interaction method must play in order to use a service page (accessible through the domain name) and guarantees the parent page and sub-pages in the same domain, or are being given the

Parent page calls subpages

When after obtaining ifram of the parent page id or calss can get the elements and methods subpages by contentWindow this object parent page call to the elements and methods of sub-pages, must wait iframe is loaded, or in onload method of performing in, or is get less than!

contentWindow can get the window object child window.
document.getElementById ( 'main') contentWindow.document.querySelector ( "warp.");. // Get parent page Method
. Document.getElementById ( 'main') contentWindow.childFn (); // get subpage method and performing

Subpages call the parent page

In sub-page by window.parent.fn () you can get and execute the parent page method

window.parent.parentFn() 

Example:

Parent page

<iframe scrolling="no" id="main" name="main" frameborder="0" src="iframe子页面1.html"></iframe>
        <script type="text/javascript">
            // ID acquired iframe object according 
            var IFR = document.getElementById ( 'main' );
            ifr.onload = function () {
                 / * Get subpage dom element * / 
                var Warp = ifr.contentWindow.document.querySelector ( "Warp."); // get the elements subpage 
                console.log (warp);        
                ifr.contentWindow.childFn ()     // method call subpages     
            }
            
            function parentFn(){
                Alert ( "I'm a method of the parent page" )                
            }        
 </script> 

Subpage

 <p onclick="parentFn">购物车</p>
    <script>
        var box=document.querySelector("p");
        box.onclick=function(){
            window.parent.parentFn () // call the parent page when clicking method
        }       

        function childFn(){
            console.log ( " I'm a method of sub-pages " )
        }
    </script>

 

Guess you like

Origin www.cnblogs.com/zimengxiyu/p/12181207.html