我的案例:localStorage键+值,当浏览器关闭时应该删除,而不是单个选项卡。

请看看我的代码,如果它是正确的和什么可以改进:

//创建localStorage key + value if (localStorage) { localStorage。myPageDataArr = { "name" => "Dan", "lastname" => "Bonny" }; } //当浏览器关闭时- psedocode $(窗口).unload(函数(){ localStorage。myPageDataArr = undefined; });


当前回答

    if(localStorage.getItem("visit") === null) {
      localStorage.setItem('visit', window.location.hostname);
      console.log(localStorage.getItem('visit'));
    } 
      else if(localStorage.getItem('visit') == 'localhost'){
            console.log(localStorage.getItem('visit'));
      }
    else {
     console.log(localStorage.getItem('visit'));
    }
   $(document).ready(function(){
      $("#clickme").click(function(){
         localStorage.setItem('visit', '0');
      });
   });  
   window.localStorage.removeItem('visit');

其他回答

在这个问题被提出6年后,我发现这个问题仍然没有足够的答案;这应该实现以下所有:

关闭浏览器(或域的所有选项卡)后清除本地存储 如果至少有一个选项卡保持活动状态,则跨选项卡保留本地存储 重新加载单个选项卡时保留本地存储

在每个页面加载开始时执行这段javascript代码,以实现上述目标:

((nm,tm) => {
    const
            l = localStorage,
            s = sessionStorage,
            tabid = s.getItem(tm) || (newid => s.setItem(tm, newid) || newid)((Math.random() * 1e8).toFixed()),
            update = set => {
                let cur = JSON.parse(l.getItem(nm) || '{}');
                if (set && typeof cur[tabid] == 'undefined' && !Object.values(cur).reduce((a, b) => a + b, 0)) {
                    l.clear();
                    cur = {};
                }
                cur[tabid] = set;
                l.setItem(nm, JSON.stringify(cur));
            };
    update(1);
    window.onbeforeunload = () => update(0);
})('tabs','tabid');

编辑:这里的基本思想如下:

When starting from scratch, the session storage is assigned a random id in a key called tabid The local storage is then set with a key called tabs containing a object those key tabid is set to 1. When the tab is unloaded, the local storage's tabs is updated to an object containing tabid set to 0. If the tab is reloaded, it's first unloaded, and resumed. Since the session storage's key tabid exists, and so does the local storage tabs key with a sub-key of tabid the local storage is not cleared. When the browser is unloaded, all session storage will be cleared. When resuming the session storage tabid won't exists anymore and a new tabid will be generated. Since the local storage does not have a sub-key for this tabid, nor any other tabid (all session were closed), it's cleared. Upon a new created tab, a new tabid is generated in session storage, but since at least one tabs[tabid] exists, the local storage is not cleared

有五种方法可供选择:

setItem():将键和值添加到localStorage getItem():通过键从localStorage检索值 removeItem():按键从localStorage中删除一个项 clear():清除所有localStorage key():传递一个数字来检索localStorage的第n个键

您可以使用clear(),该方法在调用时清除该域的所有记录的整个存储。它不接收任何参数。

window.localStorage.clear();

There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help. The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining. If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried. In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser. I ended up using a custom code and logic that takes advantage of both.

I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened. This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'. At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab. Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab. So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh. Instead you need to store a flag in sessionStorage at every load before increasing the tab counter. Before storing this value, you can make a check to see if it already has a value and if it doesn't, this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.

这是一个老问题,但上面的答案似乎都不完美。

如果您希望存储身份验证或任何敏感信息,这些信息仅在浏览器关闭时被销毁,那么您可以依赖sessionStorage和localStorage进行跨选项卡消息传递。

基本上,这个想法是:

You bootstrap from no previous tab opened, thus both your localStorage and sessionStorage are empty (if not, you can clear the localStorage). You'll have to register a message event listener on the localStorage. The user authenticate/create a sensitive info on this tab (or any other tab opened on your domain). You update the sessionStorage to store the sensitive information, and use the localStorage to store this information, then delete it (you don't care about timing here, since the event was queued when the data changed). Any other tab opened at that time will be called back on the message event, and will update their sessionStorage with the sensitive information. If the user open a new tab on your domain, its sessionStorage will be empty. The code will have to set a key in the localStorage (for exemple: req). Any(all) other tab will be called back in the message event, see that key, and can answer with the sensitive information from their sessionStorage (like in 3), if they have such.

请注意,此方案不依赖于窗口。Onbeforeunload事件是脆弱的(因为浏览器可以关闭/崩溃而不触发这些事件)。此外,敏感信息存储在localStorage上的时间非常短(因为您依赖于跨选项卡消息事件的transcients更改检测),因此此类敏感信息不太可能泄漏到用户的硬盘驱动器上。

下面是这个概念的演示:http://jsfiddle.net/oypdwxz7/2/

window.addEventListener('beforeunload', (event) => {

    localStorage.setItem("new_qus_id", $('.responseId').attr('id'));

    var new_qus_no = localStorage.getItem('new_qus_id');
    console.log(new_qus_no);

});

if (localStorage.getItem('new_qus_id') != '') {
    var question_id = localStorage.getItem('new_qus_id');
} else {
    var question_id = "<?php echo $question_id ; ?>";
}