JavaScript 跨域:window.postMessage 實現跨域通訊

    JavaScript 跨域方式實現方式有不少,以前,一篇文章中提到了 JSONP 形式實現跨域。本文將介紹 HTML5 新增的 api 實現跨域:window.postMessage 。javascript

  

 1 otherWindow.postMessage(message, targetOrigin);
 2 
 3 otherWindow
 4 其餘窗口的一個引用,好比iframe的contentWindow屬性、執行window.open返回的窗口對象、或者是命名過或數值索引的window.frames。
 5 
 6 message
 7 將要發送到其餘 window的數據。將會被結構化克隆算法序列化。這意味着你可不受什麼限制的安全傳送數據對象給目標窗口而無需本身序列化。
 8 
 9 targetOrigin
10 該參數可設置爲 *,將無域名限制。也可指定特定的域名,好比:http://www.jj.com
11 
12 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

 

    本文仍是以 iframe 爲例,一個 html 頁面中套有一個 iframe 文檔,不過,iframe 文檔 src 屬性與 html 頁面不一樣域,所以,二者之間便造成跨域。html

 

     index.html _http://localhost:3127/index.htm java

<!DOCTYPE html >
<html >
<head>
    <title></title>
</head>
<body >
   <input type="text"  id="val"/>
    <input type="button" id="btn" value="測試" /><br/>
    
    <iframe src="http://localhost:10528/index.html" > </iframe>
    <script type="text/javascript">
        window.onload = function () {
// 首先,給按鈕綁定 click 事件
if (window.addEventListener)
document.getElementById(
'btn').addEventListener('click', sendMsg, false); else document.getElementById('btn').attachEvent("onclick", sendMsg); };
// 獲取 iframe 標籤,利用 postMessage 跨域通訊,值爲 input text 標籤值
function sendMsg() { document.getElementsByTagName('iframe')[0].contentWindow.postMessage(document.getElementById('val').value,"*"); } </script> </body> </html>

 

  index.html (iframe) _http://localhost:10528/index.html算法

<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

</head>
<body >
   <b>我是另外一個跨中 iframe 文檔</b>
    <script type="text/javascript">

// 給 iframe 文檔綁定 message 事件 window.onload = function () { if (window.addEventListener) window.addEventListener('message', getMessage, false); else window.attachEvent("onmessage", getMessage); };
// iframe 觸發 message 事件時,調用 getMessage 函數
function getMessage(event) { console.dir(event); alert(event.data); } </script> </body> </html>


 

參考文檔:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessageapi

相關文章
相關標籤/搜索