I've encountered the following issue in the Safari 5.0 (not in all WebKit-based browsers), this code:
<html>
<script>
var onstorage = function(evt) {
alert([evt.key, evt.oldValue, evt.newValue].join('\n'));
}
var onclick = function(evt) {
localStorage.setItem('test', Math.random());
}
var oninit = function() {
//actually, it works the same way with old "plain event" onclick
document.querySelector('#test').addEventListener('click', onclick, false);
window.addEventListener('storage', onstorage, false);
}
</script>
<body onload="oninit()">
<input id="test" type="button" value="setting a random value"/>
</body>
will trigger on alert, in case we click the button. While this code -
<html>
<script>
var onstorage = function(evt) {
alert([evt.key, evt.oldValue, evt.newValue].join('\n'));
}
var onclick = function(evt) {
localStorage.setItem('test', Math.random());
}
var oninit = function() {
window.addEventListener('storage', onstorage, false);
//actually, it works the same way with old "plain event" onclick
document.querySelector('#test').addEventListener('click', onclick, false);
}
</script>
<body onload="oninit()">
<input id="test" type="button" value="setting a random value"/>
</body>
triggers few alerts, as not expected. I do think this is a bug, but can't somebody explain me - why swapping just two lines of codes results in such a weird behaviour?
There is no bug (although like others have commented I would not name the event handlers as global functions with names that might confuse).
The issue is how the notifications for localStorage work. In essence, events are only fired for other windows (or tabs) that use the same localStorage.
Here's a similar question and answer here on StackOverflow.
So, in your example, the storage changed event won't fire: the handler is on the same page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With