强制localStorage事件在不同的窗口中触发

时间:2014-09-11 15:14:24

标签: jquery html5 javascript-events event-handling local-storage

当用户点击链接时,它会打开一个页面,将一些内容添加到本地存储,然后刚打开的页面应该监听localStorage事件。它似乎没有触发,因为我知道必须同时打开两个窗口才能触发存储事件。所以我试着像这样手动调用它:

//page containing the link to other window

$('.view-btn').click(function () {
            var selectionName = $(this).parent().parent().find('td:first').text();
            var key = "sel-view-1";
            addToStorage(key, selectionName);          
});



var addToStorage = function (key, value) {
                defineKey(key, value);

                var e = $.Event("storage");
                e.originalEvent = {
                    key: key,
                    newValue: value
                };
                var windowRef = window.open("Create_a_selection", "_self");
                $(windowRef).trigger(e);
            };

var defineKey = function (key, value) {
            if (localStorage.getItem(key) === null) {
                localStorage.setItem(key, value);
            } else {
                var nr = parseInt(key.substring(key.lastIndexOf('-') + 1)) + 1;
                key = 'sel-view-' + nr;
                return defineKey(key, value);
            }
        }

//page that was just opened

$(window).bind('storage', onStorageEvent);

        function onStorageEvent(storageEvent) {
            console.log('yay');
            if (storageEvent.originalEvent) {
                var key = storageEvent.originalEvent.key;
                var value = storageEvent.originalEvent.newValue;
                if (key.indexOf("sel-view") > -1) {
                    $('#selection-name-label').html(value);
                }
            }
        };

但是这仍然没有捕捉到这个事件......但是如果页面已经打开,它确实会抓住它,所以我想知道这是否可能与页面未加载有关呢?

感谢任何帮助。

0 个答案:

没有答案