Apparently inconsistent launch of onstorage in Safari

I found the following problem in 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 fire upon warning if we press the button. Although this code is

 <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 several warnings as not expected. I think this is a mistake, but someone can not explain to me why replacing only two lines of code leads to such strange behavior?

+6
javascript html5 safari
source share
1 answer

There are no errors (although, like other commentators, I would not call event handlers global functions with names that can confuse).

The problem is how notifications for localStorage work. In fact, events are fired only for other windows (or tabs) that use the same localStorage.

Here's a similar question and answer here at StackOverflow.

So, in your example, the event with the storage change does not fire: the handler is on the same page.

+1
source share

All Articles