解決Iframe跨域高度自適應,利用window.postMessage()實現跨域消息傳遞頁面高度(JavaScript)

在iframe跨域引用高度自適應這塊寫的js方式都試了無論用,最終使用的是window.postMessage() 跨域獲取高度 傳遞信息html

 

1.首先,在主頁面上使用iframe引入子頁面:也就是A.html頁面引入B.html頁面,下面看看A.htmljquery

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
        <style>
        *{
            padding: 0;
            margin: 0;
        }
    </style>
    <body>
        <div>Hello! Is A.Html</div>

        <div align=center>
            <iframe Id="frame_child" width="100%"></iframe>
        </div>
    </body>
</html>
<script>
    $(function() {
        window.onload = function() {
            var url = "http://liting397.cn/";     //要訪問子類調用地址   
            $("#frame_child").attr("src", url);
            $("#frame_child").load(function() {
                setTimeout(function() {
                    var frame = document.getElementById("frame_child").contentWindow;
                    var message = {
                        parentOrigin: window.origin,
                        msg: "收到請回復"
                    };
                    frame.postMessage(JSON.stringify(message), url);  
                    console.log('發送成功');  
                }, 2000);
                window.addEventListener("message", receiveMessage, false);
            });
        }
        var receiveMessage = function(event) {
            //if (event.origin !== event.data.Domain)
            //     return; 
            console.log("子頁面有消息來了");
            $("#frame_child").attr("height", event.data + 'px');
            window.removeEventListener("message", receiveMessage, false);
        }
    })
</script>
View Code

2.子頁面代碼塊js下邊是B.html頁面,B.html頁面跨域

<script>
    //本ifram爲自適應js  使用postMessage  像父類傳遞消息   
    $(function() {
        window.addEventListener('message', function(event) {
            const data = JSON.parse(event.data)
            if (event.origin !== data.parentOrigin) {
                return
            }
            event.source.postMessage(document.body.scrollHeight, event.origin);
        }, false);
    });
</script>
View Code

這裏是寫好的ifram引用地址 能夠參考  http://liting400.cn/app

相關文章
相關標籤/搜索