window.postMessage()實現(iframe嵌套頁面)跨域消息傳遞


window.postMessage()方法可以安全地實現Window對象之間的跨域通信。例如,在頁面和嵌入其中的iframe之間。

不同頁面上的腳本允許彼此訪問,當且僅當它們源自的頁面共享相同的協議,端口號和主機(也稱為“同源策略”)。window.postMessage()提供了一個受控的機制相對來安全地規避這個限制。

發送消息的基本語法:

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

targetWindow就是接收消息的窗口的引用。 獲得該引用的方法包括:
  • Window.open
  • Window.opener
  • HTMLIFrameElement.contentWindow
  • Window.parent
  • Window.frames +索引值

message就是要發送到目標窗口的消息。 數據使用結構化克隆算法進行序列化。 這意味着我們可以將各種各樣的數據對象安全地傳遞到目標窗口,而無需自己對其進行序列化。

targetOrigin就是指定目標窗口的來源,必須與消息發送目標相一致,可以是字符串“*”或URI。 *表示任何目標窗口都可接收,為安全起見,請一定要明確提定接收方的URI。

transfer是可選參數

接收端:

 

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event){
  if (event.origin !== "http://127.0.0.1:3808/")
    return;
}
 
event對象有三個屬性,分別是origin,data和source。event.data表示接收到的消息;event.origin表示postMessage的發送來源,包括協議,域名和端口;event.source表示發送消息的窗口對象的引用; 我們可以用這個引用來建立兩個不同來源的窗口之間的雙向通信。

完整示例:

1、父頁面

  <title>father</title>
</head>
<body>
  <div style="width: 200px;float: left;margin-right: 200px;border: 1px solid #333;">
    <div id="color"> frame color</div>
  </div>
  <div>
    <iframe id="child" src="http://127.0.0.1:3808/iframe-son/index.html"></iframe>
  </div>
  <script>
    window.onload = function() {
      // 初始化div顏色
      window.frames[0].postMessage('getcolor', 'http://127.0.0.1:3808/');
    }

    window.addEventListener('message',function(e) {
      // 監聽子頁面顏色的改變即發送的消息,設置div顏色
      var color = e.data;
      document.getElementById('color').style.backgroundColor = color;
    },false)
  </script>
</body>
</html>

 2、子頁面

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>son</title>
</head>
<body>
  <div id="container" onclick="changeColor();" style="width: 100%; height: 100%;background-color: rgb(204,102,0)">
    click to change color
  </div>

  <script>
    var container = document.getElementById('container');

    //監聽父頁面傳遞過來的信息
    window.addEventListener('message', function (e) {
      if(e.source != window.parent) return ;
      // container.innerHTML = e.data

      var color = container.style.backgroundColor;
      window.parent.postMessage(color,'*');
    },false)

    //改變顏色的方法
    function changeColor() {
      var color = container.style.backgroundColor;
      if(color=='rgb(204, 102, 0)'){
        color='rgb(204, 204, 0)';
      }else{
        color='rgb(204,102,0)';
      }
      container.style.backgroundColor = color;
      // 給父元素發送消息
      window.parent.postMessage(color,'*');
    }
  </script>
</body>
</html>

 

 

 

 


免責聲明!

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



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