storage Event | IE8-compatible

Passing messages between browser windows of the same domain

HTML

<button id="send">send</button>

JavaScript

$(function(){
    // localStorage sends a "storage" Event to all connected windows
    // this event does not bubble
    // Internet Explorer expects the event on document, 
    // specification adhering browser expect it on window
    // IE8 doesn't know storageEvent.key (.oldValue, .newValue), so it has to be faked
    // Specification:
    // http://dev.w3.org/html5/webstorage/#the-storage-event
    // http://msdn.microsoft.com/de-de/library/cc197062%28v=vs.85%29.aspx#onstorage
    // http://msdn.microsoft.com/de-de/library/cc197059.aspx
    
    var _last_sent_key = null,
        send = function(message) {
            var key = 'cdm-' + (+new Date());
            
            // event is not sent if the storage is not mutated!
            if (localStorage.getItem('rand') !== null) {
                localStorage.removeItem('rand');
            }
            
            // IE8 fix missing storageEvent.key
            if ("onstorage" in document) {
                localStorage.setItem('_last_storage_event_key', key);
            }
            
            _last_sent_key = key;
            localStorage.setItem(key, message);
        
            $('<p>sent Message[' + key + ']: ' + message + '</p>')
                .appendTo(document.body);
        },
        receive = function(e) {
            alert(' storage called');
            var value = localStorage.getItem(e.originalEvent.key);
            alert(value);
            console.log('storage called');
            if (value === null) {
                // ignore .removeStorage() events
                return;
            };
            
            $('<p>received Message[' + e.originalEvent.key + ']: ' + value + '</p>')
                .appendTo(document.body);

            // inform sender (and other listeners) that the key has been removed
            localStorage.removeItem(e.originalEvent.key);
        };
    
    $('#send').on('click', function(){ send( "Hello, it's " + (new Date()) ); });
   ...