使用 iframe + postMessage 實現跨域通信


在實際項目開發中可能會碰到在 a.com 頁面中嵌套 b.com 頁面,這時第一反應是使用 iframe,但是產品又提出在 a.com 中操作,b.com 中進行顯示,或者相反。

1、postMessage

  postMessage方法允許來自不同源的腳本采用異步方式進行有限的通信,可以實現跨文本檔、多窗口、跨域消息傳遞。

語法:

otherWindow.postMessage(message, targetOrigin, [transfer]);
  • otherWindow:其他窗口的引用,如 iframe的contentWindow、執行window.open返回的窗口對象、或者是命名過或數值索引的window.frames。
  • message:將要發送到其他window的數據。
  • targetOrigin:指定那些窗口能接收到消息事件,其值可以是字符串 “*” 表示無限制,或者是一個URI。
  • transfer:是一串和message同時傳遞的Transferable對象,這些對象的所有權將被轉移給消息的接收方,而發送方將不再保留所有權。

postMessage方法被調用時,會在所有頁面腳本執行完畢之后像目標窗口派發一個 MessageEvent 消息,該MessageEvent消息有四個屬性需要注意:

  • type:表示該message的類型
  • data:為 postMessage 的第一個參數
  • origin:表示調用postMessage方法窗口的源
  • source:記錄調用postMessage方法的窗口對象

parent.html

<!DOCTYPE html> 
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage 跨域通信 主頁面</title>
</head>
<body>
    <h1>主頁面</h1>
    <iframe id="child" src="./child.html"></iframe>
    <div>
        <h2>主頁面接收消息區域</h2>
        <span id="message"></span>
    </div>
</body> 
<script>
    window.onload = function(){
        document.getElementById('child')
         .contentWindow.postMessage("主頁面消息","http://192.168.23.10:9000/child.html")//父向子傳遞
    }
    window.addEventListener('message', function(event){//父獲取子傳遞的消息
        document.getElementById('message').innerHTML = "收到"
         + event.origin + "消息:" + event.data;
    }, false)
</script>
</html>

  child.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage跨域通信 子頁面</title>
</head>
<body>
    <h2>子頁面</h2>
    <div>
        <h3>接收消息區域</h3>
        <span id="message"></span>
    </div>
</body>
<script>
    window.addEventListener('message',function(event){//子獲取父消息
        console.log(event);
        document.getElementById('message').innerHTML = "收到" + event.origin + "消息:" + event.data;
        console.log(top)
        top.postMessage("子頁面消息收到", 'http://192.168.23.10:9000/parent.html')//父向子消息
    }, false);
</script>
</html>

  注:不支持file協議

 


免責聲明!

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



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