2013-02-06 40 views
2

是否有可能在瀏覽器標籤頁/窗口之間有基於事件的通信?瀏覽器窗口之間可以進行基於事件的通信嗎?

我知道它可以(至少在理論上)使用本地存儲。你能提供一個小例子來做這個嗎?只需在一個標籤中發送活動,並在另一個標籤中接收活動。

是否有任何庫/ jQuery插件可以做到這一點?我知道我可以使用cookie在同一個瀏覽器的窗口/標籤之間進行通信,但這不是我所需要的;我更喜歡基於事件的方法,我不想每隔一段時間重新檢查一次cookie的狀態毫秒)。

+1

看看[postMessage](https://developer.mozilla.org/en-US/docs/DOM/window.postMessage) –

+0

@FabrícioMatté我不認爲這將工作的標籤,因爲你需要一個參考窗口:https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage#Syntax – edhedges

回答

7

本地存儲具有可以訂閱以同步其他頁面的事件。

注:如果您在窗口中的更新鍵的值,該事件將不會窗口A.觸發它會在Windows b都是觸發& C.

這裏是一個演示: http://html5demos.com/storage-events

在多個選項卡中打開此頁面。改變輸入的值,並看到它反映在div中。

下面是代碼的JavaScript:

var dataInput = document.getElementById('data'), 
output = document.getElementById('fromEvent'); 

// handle updates to the storage-event-test key in other windows 
addEvent(window, 'storage', function (event) { 
    if (event.key == 'storage-event-test') { 
    output.innerHTML = event.newValue; 
    } 
}); 

// Update the storage-event-test key when the value on the input is changed 
addEvent(dataInput, 'keyup', function() { 
    localStorage.setItem('storage-event-test', this.value); 
}); 

標記:

<div> 
     <p>Your test data: <input type="text" name="data" value="" placeholder="change me" id="data" /> <small>(this is only echoed on <em>other</em> windows)</small></p> 
     <p id="fromEvent">Waiting for data via <code>storage</code> event...</p> 
</div> 

的HTML 5規範介紹了該事件傳遞的所有信息:

[Constructor(DOMString type, optional StorageEventInit eventInitDict)] 
interface StorageEvent : Event { 
    readonly attribute DOMString key; 
    readonly attribute DOMString? oldValue; 
    readonly attribute DOMString? newValue; 
    readonly attribute DOMString url; 
    readonly attribute Storage? storageArea; 
}; 

dictionary StorageEventInit : EventInit { 
    DOMString key; 
    DOMString? oldValue; 
    DOMString? newValue; 
    DOMString url; 
    Storage? storageArea; 
}; 

來源:http://www.w3.org/TR/webstorage/#the-storage-event

使用此事件,可以使其他頁面在本地存儲中的特定密鑰更新時作出反應。

0

SignalRamp一個機會。

您可以將任何可綁定類名稱附加到元素以同步相應的mousedown,mouseup,hover(mouseover,mouseout)或單擊UI中的事件。

相關問題