window.postMessage()方法能夠安全地實現Window對象之間的跨域通訊。例如,在頁面和嵌入其中的iframe之間。javascript
不一樣頁面上的腳本容許彼此訪問,當且僅當它們源自的頁面共享相同的協議,端口號和主機(也稱爲「同源策略」)。window.postMessage()提供了一個受控的機制相對來安全地規避這個限制。
發送消息的基本語法:
targetWindow.postMessage(message, targetOrigin, [transfer]);
- Window.open
- Window.opener
- HTMLIFrameElement.contentWindow
- Window.parent
- Window.frames +索引值
message就是要發送到目標窗口的消息。 數據使用結構化克隆算法進行序列化。 這意味着咱們能夠將各類各樣的數據對象安全地傳遞到目標窗口,而無需本身對其進行序列化。html
targetOrigin就是指定目標窗口的來源,必須與消息發送目標相一致,能夠是字符串「*」或URI。 *表示任何目標窗口均可接收,爲安全起見,請必定要明確提定接收方的URI。java
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表示發送消息的窗口對象的引用; 咱們能夠用這個引用來創建兩個不一樣來源的窗口之間的雙向通訊。
完整示例:安全
一、父頁面post
<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>
二、子頁面ui
<!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>