Sonny
Sonny

Reputation: 8326

Internet Explorer Showing Old Values For Local Storage

I'm handling the storage event to synchronize changes across browser windows. I've noticed that Internet Explorer seems to keep the old values.

Example HTML

<ul>
    <li data-aid="1" data-pid="1">1/1</li>
    <li data-aid="1" data-pid="2">1/2</li>
    <li data-aid="2" data-pid="3">2/3</li>
    <li data-aid="2" data-pid="4">2/4</li>
</ul>

Example JS

$(document).ready(function() {
    localStorage.removeItem('li');
    $('li').on('click', function() {
        var $this = $(this);
        localStorage.setItem('li', JSON.stringify({
            aid : $this.data('aid'),
            pid : $this.data('pid')
        }));
    });
    $(window).on('storage', function(e) {
        // ignore Internet Explorer firing event in own window
        // ignore changes not to the 'li' key
        if (!document.hasFocus() && ('li' === e.originalEvent.key)) {
            $('body').append('<p>' + localStorage.getItem('li') + '</p>');
        }
    });
});

If I have two windows open, and click each list item, the second window has the following output:

<p>null</p>
<p>{"aid":1,"pid":1}</p>
<p>{"aid":1,"pid":2}</p>
<p>{"aid":2,"pid":3}</p>

In Chrome, Firefox, and Safari I get the output I expect:

<p>{"aid":1,"pid":1}</p>
<p>{"aid":1,"pid":2}</p>
<p>{"aid":2,"pid":3}</p>
<p>{"aid":2,"pid":4}</p>

Upvotes: 0

Views: 1368

Answers (1)

Sonny
Sonny

Reputation: 8326

While digging through a tutorial, I saw that the storage event has a newValue property. Changing my listener to use that, instead of reading from localStorage, fixes the issue in Internet Explorer. It works in all the other browsers too!

$(document).ready(function() {
    localStorage.removeItem('li');
    $('li').on('click', function() {
        var $this = $(this);
        localStorage.setItem('li', JSON.stringify({
            aid : $this.data('aid'),
            pid : $this.data('pid')
        }));
    });
    $(window).on('storage', function(e) {
        // ignore Internet Explorer firing event in own window
        // ignore changes not to the 'li' key
        if (!document.hasFocus() && ('li' === e.originalEvent.key)) {
            // use the event's newValue property instead of reading from storage
            // fixes issue with IE returning old value
            $('body').append('<p>' + e.originalEvent.newValue + '</p>');
        }
    });
});

UPDATE

I found two SO posts have solutions that fix the problem by introducing a slight delay. I feel that my solution is a bit more elegant.

Upvotes: 5

Related Questions