iframe 父子間傳值通信


1、同域 iframe 父子間傳值

(1)父頁面

<html>
<head>
    <script type="text/javascript">
        function say(){
            alert("parent.html");
        }
        function callChild(){
            myFrame.window.say();
            myFrame.window.document.getElementById("button").value="調用結束";
        }
    </script>
</head>
<body>
    <input id="button" type="button" value="調用child.html中的函數say()" onclick="callChild()"/>
    <iframe name="myFrame" src="child.html"></iframe>
</body>
</html>

(2)子頁面

<html>
<head>
    <script type="text/javascript">
        function say(){
            alert("child.html");
        }
        function callParent(){
            parent.say();
            parent.window.document.getElementById("button").value="調用結束";
        }
    </script>
</head>
<body>
    <input id="button" type="button" value="調用parent.html中的say()函數" onclick="callParent()"/>
</body>
</html>

總結:方法調用

父頁面調用子頁面方法:FrameName.window.childMethod();

子頁面調用父頁面方法:parent.window.parentMethod();

2、跨域 iframe 父子間傳值

(1)父頁面

<template>
    <div>
        <iframe 
         :src="iframesrc" 
         id="a-page"></iframe>
    </div>
</template>

<script>
export default {
    computed:{
        iframesrc:function(){
            let iframesrc = "http://b.com"
            return iframesrc
        }
    },
    created () {
        // 得到B傳來的值 
        window.addEventListener('message',function(e){
            console.log("B DOM的高度", e.data)
        },false);
        // 監聽A頁面的事件,發送給B
        window.addEventListener('scroll', function () {
            let iframe = document.getElementById('a-page');
            
            let json = {
                scrollTop: scrollTop,
                windowHeight: windowHeight,
            };
            iframe.contentWindow.postMessage(json, '*');
        });
    }
}
</script>

(2)子頁面

<template>
    <div>
        <div id="b-page"></div>
    </div>
</template>

<script>
export default {
    mounted() {
        // 獲取到B頁面的值,發送給A
        let _this = this
        let b_pageH = document.getElementById('b-page').scrollHeight;
        window.parent.postMessage(b_pageH, '*'); // 得到A頁面的值
        window.addEventListener('message',function(e){
            console.log("e.data.scrollTop", e.data.scrollTop)
            console.log("e.data.windowHeight", e.data.windowHeight) 
        },false);
    }
}
</script>

 


免責聲明!

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



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