I need to be notified when localStorage
is changed. This code works fine in Firefox 24, but doesn't work in Chrome 29 (or 30) or in IE 10. It also works on a live server, but not when I am testing using a local file (file:///
).
Here is the code:
<!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>
What is the problem with this in Chrome? I'm opening two tabs as required.
It will only fire the event in the "other" tabs/windows but not in the one changing the data (this is a bit unclear in your question so please correct me if I misunderstood).
Source W3C
Update to complete the answer based on comments:
There will be restrictions in some browsers if the page is running from the file protocol (
file:///
) due to security reasons.In Chrome you can override this by supplying the argument
--allow-file-access-from-files
:I'm not sure if you can do something similar with other browsers. I would recommend testing with a local server (e.g. such as Mongoose) in order to not run into any surprises in a live scenario.