首页 > 解决方案 > 在 firefox 的同一个选项卡上触发“storage”事件

问题描述

2013 年,我编写了一段代码,阻止用户在同一个域上打开第二个浏览器选项卡,直到一年前它运行良好。它基于应该在第二个窗口写入 localStorage 时触发的“存储”事件。这是代码:

$(function(){

    var this_tab_key =  randomString(30);
    var listener = function(e){

        if(e.key=='test_block' && e.newValue != this_tab_key)
        {
            STOP_AJAX_CALLS = true;
            var div = $('<div id="modal_block" style="top:0px;left:0px;position:absolute;width:100%;height:100%;opacity:0.5;background-color:black;z-index:12000"></div>');
            div.append('<div style="position:absolute;top:50%;left:0;width:100%;font-size:60px;margin-top:-50px;text-align:center;line-height:50px;" >Please close this tab/windows <br>as another one has been opened</div>');
            $("body").append(div);
            if (window.removeEventListener) 
                window.removeEventListener("storage", listener);
            else
                window.detachEvent("onstorage", listener);
        }
    };

    if (window.addEventListener)
        window.addEventListener("storage", listener);
    else
        window.attachEvent("onstorage", listener);

    localStorage.setItem('test_block', this_tab_key);
});

最近发生的情况是,即使我只打开了一个选项卡,也会触发“存储”事件,但并非总是如此,并且它通常在我打开选项卡后 3/5 分钟后发生。没有 ajax/ws 调用,站点中一般没有活动。页面中没有 iframe,因此没有其他“窗口”对象。它似乎只发生在 Firefox 中,但他们告诉我它也可能发生在 chrome 中,即使我从未亲眼见过它。你知道这里发生了什么吗?

提前致谢

标签: javascriptlocal-storage

解决方案


推荐阅读