jcubic
jcubic

Reputation: 66590

how to detect if localStorage storage event came from same page in IE?

I have a library sysend.js that allow to send messages to other tabs/windows using storage event. Bu in IE the event is fired also on same page that use setItem. Is there a way to detect in IE if storage event fired on same or different page?

My code for storage event look like this:

var uniq_prefix = '___sysend___';
function get(key) {
    return localStorage.getItem(uniq_prefix + key);
}
var callbacks = {};
window.addEventListener('storage', function(e) {
    // get user key
    var key = e.key.replace(new RegExp('^' + uniq_prefix), '');
    if (callbacks[key]) {
        var obj = JSON.parse(get(key));
        if (obj) {
            // don't call on remove
            callbacks[key].forEach(function(fn) {
                fn(obj[1], key);
            });
        }
    }
}, false);

data in localStorage is array with id as first item and actual data as second item.

Upvotes: 1

Views: 284

Answers (1)

jcubic
jcubic

Reputation: 66590

You can check if event url is different then location.href:

window.addEventListener('storage', function(e) {
    if (e.url != location.href) {
        var key = e.key.replace(re, '');
        if (callbacks[key]) {
            var value = e.newValue || get(key);
            if (value != random_value) {
                var obj = JSON.parse(value);
                if (obj) {
                    // don't call on remove
                    callbacks[key].forEach(function(fn) {
                        fn(obj[1], key);
                    });
                }
            }
        }
    }
}, false);

Upvotes: 1

Related Questions