iframe之父子頁面通信


iframe之父子頁面通信

1、獲取 子頁面 的 window 對象 

在父頁面中,存在如下兩個對象

window.frames

document.iframeElement.contentWindow

可以獲取到 子頁面 window 對象

// iframe id
document.getElementById('menuIframe').contentWindow

// iframe name
window.frames['menuIframe'].window

// iframe index 當前窗體的第幾個 iframe
window.frames[1].window

既然拿到了 window 對象,那函數和DOM就到手了。

2、子 iframe 獲取 父頁面

window.parent 對象

window.top對象

// 判斷當前頁面是否是 iframe 或 頂級頁面 window.parent == window window.top == window

window.parent 即為當前頁面的上一級頁面的 window 對象,如果當前頁面已是 頂層 頁面,則 window.parent 就是自己。

3、小實例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <iframe src="/sub.html" name="iframeContainer" id="iframeContainer"></iframe>
    <script type="text/javascript">
        function parentHello() {
            alert("this is parent hello function!");
        }
        window.frames['iframeContainer'].subHello();
    </script>
</body>
</html>

<!-- sub.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        function subHello() {
            alert("this is sub hello function!");
        }

        window.parent.parentHello();
    </script>
</body>
</html>

  

 

轉載自:https://my.oschina.net/sallency/blog/1618971

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM