2013-10-03 54 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的选项卡上进行监听。 –

相关问题