2013-10-03 53 views
10

我需要在localStorage發生更改時收到通知。此代碼在Firefox 24中正常工作,但在Chrome 29(或30)或IE 10中不起作用。它也適用於實時服務器,但不適用於使用本地文件(file:///)進行測試的情況。localStorage事件偵聽器不會在本地文件的Chrome中觸發

下面是代碼:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Index</title> 
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $('#submit').click(function() { 
       console.log('Clicked'); 
       if($('#username').val() != "") 
        localStorage.setItem('someItem', 'someValue'); 
      }); 
      $(window).bind('storage', function(e) { 
       alert('change'); 
      }); 


     }); 
    </script> 
</head> 
<body> 
<input type="text" id="username" name="username" value="" /> 
<a href="#" id="submit">Click me</a> 
<p id="result"></p> 
</body> 
</html> 

這有什麼在Chrome中的問題?我需要打開兩個標籤。

回答

11

它只會火在「其他」選項卡/窗口,但不是在一個不斷變化的數據的情況下(這是你的問題有點不清楚,所以請糾正我,如果我誤解)。

When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a local storage area, if the methods did something, then in every Document object whose Window object's localStorage attribute's Storage object is associated with the same storage area, other than x, a storage event must be fired, as described below.

Source W3C

更新完成基於評論答案:

在某些瀏覽器

會有限制,如果頁面從文件協議(file:///)由於安全原因運行。

在Chrome中,你可以通過提供參數--allow-file-access-from-files覆蓋此:

chrome.exe --allow-file-access-from-files 

我不知道如果你能做到與其他瀏覽器類似的東西。我會建議使用本地服務器進行測試(例如Mongoose),以免在實際場景中遇到任何意外。

+0

我從W3C閱讀說明書,我想我明白了,我的問題是我打開兩個選項卡,在TAB2,我改變的localStorage的值,但TAB1沒有任何發生。您是否嘗試過Chrome版本29? –

+0

@TrungHuynh請提供一個我可以測試的小提琴。 – K3N

+0

這是它! http://jsfiddle.net/4ftxj/!但它需要兩個標籤才能完全運行,因爲遵循規範,因此無法在更改localStorage的選項卡上進行監聽。 –

相關問題