2010-08-25 66 views
10

我試圖關注the examples on the Safari Developer Site每次在Safari 5+中更新localStorage時,如何獲得一個事件觸發?

文檔建議添加事件監聽器,如下:

window.addEventListener('storage', storage_handler, false); 

,然後設置你的處理函數是這樣的:

function storage_handler(evt) 
{ 
    alert('The modified key was '+evt.key); 
    alert('The original value was '+evt.oldValue); 
    alert('The new value is '+evt.newValue); 
    alert('The URL of the page that made the change was '+evt.url); 
    alert('The window where the change was made was '+evt.source); 
} 

但我似乎無法獲得此代碼工作的我的機器(OS X 10.6,Safari 5.01)以及我的iPhone 3GS(iOS 4.02)上的Safari。

This article提供了一個單獨的方法:

window.onload = function() { 
    ... 
    document.body.setAttribute("onstorage", "handleOnStorage();"); 
} 

function handleOnStorage() { 
    if (window.event && window.event.key.indexOf("index::") == 0){ 
     $("stats").innerHTML = ""; 
     displayStats(); 
    } 
} 

但我還沒有與任何運氣無論是。

我做錯了什麼?這是一個錯誤?

+1

我固定在你對你的問題的聯繫;一旦你得到更多的代表,你應該能夠很快添加更多的鏈接。可悲的是,我不知道你的問題的答案。希望別人能幫助! – 2010-08-25 05:09:43

+0

其代碼片段的一個很好的演示已經可以[在這裏](http://html5demos.com/storage-events)瞭解這個概念以及它是如何工作的。 http://html5demos.com/storage-events – msoliman 2015-09-19 21:33:12

+0

仍然有這個鏈接,可能也有助於理解sessionStorage很好https://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/ – msoliman 2015-09-20 11:14:59

回答

19

經過進一步調查(並在朋友的幫助下),我發現當本地存儲值的值在當前窗口或選項卡中的頁面上發生更改時,調用storage_handler方法時,但在另一個選項卡中更改時。例如,如果我打開了兩個選項卡,並且在每個選項卡的頁面中都有控件來更改本地存儲設置,那麼當我在第一個選項卡中選中控件時,將在另一個選項卡中調用storage_handler方法。

+0

您是否找到可靠的來源?你能提供給我們嗎? 我無法從規範https://www.w3.org/TR/webstorage/#sessionStorageEvent推斷出。但無論如何,我在解釋時遇到了困難,特別是它提到「完全活躍」文檔的部分。 – leods92 2017-04-25 19:17:49

2

如果要在對象保存在本地存儲中的對象保存在同一頁面後執行某些操作,則可以在調用localStorage.setItem後手動調用該函數,並調用storage eventlistener中的相同函數來處理多個選項卡。

相關問題