語法:

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

 

otherWindow
其他窗口的一個引用,比如iframe的contentWindow屬性、執行window.open返回的窗口對象、或者是命名過或數值索引的window.frames。
message
將要發送到其他window的數據。它將會被結構化克隆算法序列化。這意味著你可以不受什麼限制的將數據對象安全的傳送給目標窗口而無需自己序列化。
targetOrigin
通過窗口的origin屬性來指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示無限制)或者一個URI。在發送消息的時候,如果目標窗口的協議、主機地址或端口這三者的任意一項不匹配targetOrigin提供的值,那麼消息就不會被發送;只有三者完全匹配,消息才會被發送。這個機制用來控制消息可以發送到哪些窗口;例如,當用postMessage傳送密碼時,這個參數就顯得尤為重要,必須保證它的值與這條包含密碼的信息的預期接受者的orign屬性完全一致,來防止密碼被惡意的第三方截獲。如果你明確的知道消息應該發送到哪個窗口,那麼請始終提供一個有確切值的targetOrigin,而不是*。不提供確切的目標將導致數據洩露到任何對數據感興趣的惡意站點。
transfer 可選
是一串和message同時傳遞的 Transferable對象.這些對象的所有權將被轉移給消息的接收方,而發送一方將不再保有所有權。

 

The dispatched event:
執行如下代碼, 其他window可以監聽派遣的message:

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  // For Chrome, the origin property is in the event.originalEvent
  // object.
  var origin = event.origin || event.originalEvent.origin; 
  if (origin !== "http://example.org:8080")
    return;

  // ...
}

 

示例:

/*
 * A窗口的域名是<http://example.com:8080>,以下是A窗口的script標籤下的代碼:
 */

var popup = window.open(...popup details...);

// 如果彈出框沒有被阻止且加載完成

// 這行語句沒有發送信息出去,即使假設當前頁面沒有改變location(因為targetOrigin設置不對)
popup.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");

// 假設當前頁面沒有改變location,這條語句會成功添加message到發送隊列中去(targetOrigin設置對了)
popup.postMessage("hello there!", "http://example.org");

function receiveMessage(event)
{
  // 我們能相信信息的發送者嗎? (也許這個發送者和我們最初打開的不是同一個頁面).
  if (event.origin !== "http://example.org")
    return;

  // event.source 是我們通過window.open打開的彈出頁面 popup
  // event.data 是 popup發送給當前頁面的消息 "hi there yourself! the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);
/*
 * 彈出頁 popup 域名是<http://example.org>,以下是script標籤中的代碼:
 */

//當A頁面postMessage被調用後,這個function被addEventListenner調用
function receiveMessage(event)
{
  // 我們能信任信息來源嗎?
  if (event.origin !== "http://example.com:8080")
    return;

  // event.source 就當前彈出頁的來源頁面
  // event.data 是 "hello there!"

  // 假設你已經驗證了所受到信息的origin (任何時候你都應該這樣做), 一個很方便的方式就是把enent.source
  // 作為回信的對象,並且把event.origin作為targetOrigin
  event.source.postMessage("hi there yourself! the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);

 

原文:Window.postMessage() - Web APIs | MDN


 

HTML5 的 postMessage 能在不同網頁中傳送資料,也能跨網域傳送資料。
下面的範例,是先從某一個網頁,使用 window.open 開啟另一個網域的頁面,再將文字訊息傳送過去。
(若要傳送給 iframe 的頁面,可以使用 contentWindow 取得 iframe 載入的頁面,就可以用相同的方式傳送。)

傳送文字訊息頁面:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>HTML5 使用postMessage在不同網頁之間傳送文字訊息(傳送頁面)</title>
        <style>
        </style>
        <script>
            var new_win;

            /* 開啟另一個網頁 */
            function openWin() {
                new_win = window.open("http://demo2.cinc.biz/html5-postmessage/text-new.html");
            }

            /* 傳送文字訊息 */
            function sendMsg() {
                var msg = document.getElementById("msg_txt").value;
                new_win.postMessage(msg, "http://demo2.cinc.biz");//表示要送給demo2.example.com網域
            }
        </script>
    </head>
    <body>
        HTML5 使用postMessage在不同網頁之間傳送文字訊息(傳送頁面)<br>
        測試範例:<br>
        1.<button onclick="openWin()">開啟接收訊息頁面</button><br>
        2.<input id="msg_txt"  type="text" value="msg test"/>
        <button onclick="sendMsg()">傳送文字訊息到接收頁面</button>
    </body>
</html>

 

接收文字訊息頁面:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>HTML5 使用postMessage在不同網頁之間傳送文字訊息(接收頁面)</title>
        <style>
        </style>
        <script>
            var myMsg = function(e) {
                alert("接收到的訊息:" + e.data);
                alert("訊息來源網域:" + e.origin);
                if (e.origin != "http://demo.cinc.biz") {
                    alert("不明來源,不處理");
                    return; //不明來源,不處理
                }

                document.getElementById("res").innerHTML = "接收到的訊息:" + e.data;
            };
            window.addEventListener("message", myMsg, false);//監聽message事件
        </script>
    </head>
    <body>
        HTML5 使用postMessage在不同網頁之間傳送文字訊息(接收頁面)
        <div id="res"></div>
    </body>
</html>

 

出處:HTML5 使用postMessage在不同網頁之間傳送文字訊息


 

EventTarget.addEventListener()

能將指定的事件監聽器註冊到 EventTarget 實作物件上。EventTarget 可能是 Document 中的 Element 物件、Document 物件本身、Window 物件,或是其它支援事件的物件(如:XMLHttpRequest)。

語法:

target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, wantsUntrusted  ]); // Gecko/Mozilla only

 

type
    表示所監聽的 event type 名稱之字串。
listener
    當監聽的事件發生時負責接收事件物件(Event 的實作物件)的物件。這個物件必須是事件監聽器(實作了 EventListener 介面),或是一個簡單的 JavaScript 函式。

options 可選
    一個指定有關 listener 屬性的可選參數對象。可用的選項如下:

        capture: Boolean,表示 listener 會在該類型的事件捕獲階段傳播到該 EventTarget 時觸發。
        once: Boolean,表示 listener 在添加之後最多只調用一次。如果是 true, listener 會在其被調用之後自動移除。
        passive: Boolean,表示 listener 永遠不會調用 preventDefault()。如果 listener 仍然調用了這個函數,客戶端將會忽略它並拋出一個控制台警告。
         mozSystemGroup: 只能在 XBL 或者是 Firefox' chrome 使用,這是個 Boolean,表示 listener 被添加到 system group。

useCapture 可選
    Boolean,是指在DOM樹中,註冊了該listener的元素,是否會先於它下方的任何事件目標,接收到該事件。沿著DOM樹向上冒泡的事件不會觸發被指定為use capture(也就是設為true)的listener。當一個元素嵌套了另一個元素,兩個元素都對同一個事件註冊了一個處理函數時,所發生的事件冒泡和事件捕獲是兩種不同的事件傳播方式。事件傳播模式決定了元素以哪個順序接收事件。進一步的解釋可以查看 事件流 及 JavaScript Event order 文檔。如果沒有指定, useCapture 默認為 false 。

wantsUntrusted
    如果為 true , 則事件處理程序會接收網頁自定義的事件。此參數只適用於 Gecko,主要用於附加組件的代碼和瀏覽器本身。

 

範例:
一個簡易的事件監聽

HTML 內容

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

 

JavaScript 內容

// Function to change the content of t2
function modifyText() {
  var t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);

 

匿名函數的事件監聽

HTML 內容

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

 

JavaScript 內容

// 改變 t2 內容的函數
function modifyText(new_text) {
  var t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;    
}

// 為表格增加事件監聽的函數
var el = document.getElementById("outside");
el.addEventListener("click", function(){modifyText("four")}, false);

 

原文:EventTarget.addEventListener() - Web APIs | MDN

 

 

 

 

 

arrow
arrow

    Robert 發表在 痞客邦 留言(0) 人氣()