js Iframe與父級頁面通信及IE9-兼容性


一、 postMessage

  window.postMessage()方法安全地啟用Window對象之間的跨源通信;例如,在頁面和它產生的彈出窗口之間,或者在頁面和嵌入其中的iframe之間。 

二、語法

  otherWindow.postMessage(message, targetOrigin, [transfer]);

  otherWindow:是接收對象的窗體引用,例如:子窗體(iframe)對父級窗體的引用 "window.parent" 或者其他Iframe的引用 “Window.frames +索引值(命名或數字)”

  message:將要發送到其他 window的數據。在IE9以下的瀏覽器,message不支持JSON對象,必須是字符串類型

  targetOrigin:通過窗口的origin屬性來指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示無限制)或者一個URI。在發送消息的時候,如果目標窗口的協議、主機地址或端口這三者的任意一項不匹配targetOrigin提供的值,那么消息就不會被發送;只有三者完全匹配,消息才會被發送。

  transfer:是一串和message 同時傳遞的 Transferable 對象. 這些對象的所有權將被轉移給消息的接收方,而發送一方將不再保有所有權。

三、應用子窗體和父窗體之間的通信

1. parent.html:添加有Iframe(childIframe.html) 頁面,並監聽message事件

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    <style>
        iframe{
            border:none;
            width:100%;
        }
    </style>
</head>
<body>
    <h1>parent</h1>
    <iframe src="childiframe.html"></iframe>
    <script>
        window.addEventListener("message", function (message) {
            alert(JSON.stringify(message.data));
        });
    </script>
</body>
</html>
View Code

2. childIframe.html:直接向parent 發送一條消息

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
</head>
<body>
    <h1>childIframe</h1>

    <script>
        window.parent.postMessage({type:"open",url:"iframe.html"},"*");
    </script>
</body>
</html>
View Code

3. IE9-兼容問題:

  IE9及以下的瀏覽器,message不支持JSON對象,必須是字符串類型。發送時將JSON轉換為字符串

window.parent.postMessage(JSON.stringify({ type: "open", url: "iframe.html" }), "*");

  IE9還是IE8 不兼容addEventListener和"message"監聽方法和事件,兼容辦法

//IE8,IE9兼容方法
if (window.attachEvent) {
    window.attachEvent('onmessage', function (message) {
        console.log(JSON.parse(message.data));
    });
} else {
    window.addEventListener('message', function (message) {
        console.log(JSON.parse(message.data));
    });
}


免責聲明!

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



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