Tru*_*ynh 10 javascript jquery html5 google-chrome local-storage
我需要在localStorage
更改时收到通知.此代码在Firefox 24中运行良好,但在Chrome 29(或30)或IE 10中不起作用.它也可以在实时服务器上运行,但在我使用本地文件(file:///
)进行测试时却无效.
这是代码:
<!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>
Run Code Online (Sandbox Code Playgroud)
这在Chrome中有什么问题?我根据需要打开两个标签.
小智 12
它只会在"其他"选项卡/窗口中触发事件,但不会在更改数据的情况下触发(这在您的问题中有点不清楚,所以如果我误解,请纠正我).
当在与本地存储区域相关联的存储对象x上调用setItem(),removeItem()和clear()方法时,如果方法执行了某些操作,则在Window对象的localStorage属性的Storage对象的每个Document对象中都是如果与x相同的存储区域相关联,则必须触发存储事件,如下所述.
根据评论更新完成答案:
如果页面file:///
由于安全原因从文件协议()运行,则某些浏览器会有限制.
在Chrome中,您可以通过提供参数来覆盖它--allow-file-access-from-files
:
chrome.exe --allow-file-access-from-files
Run Code Online (Sandbox Code Playgroud)
我不确定你是否可以和其他浏览器做类似的事情.我建议使用本地服务器(例如Mongoose)进行测试,以免在实时场景中遇到任何意外.