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

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

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


试着用

$(window).unload(function(){
  localStorage.clear();
});

希望这对你有用


您可以尝试以下代码删除本地存储:

delete localStorage.myPageDataArr;

应该这样做,而不是使用delete操作符:

localStorage.removeItem(key);

你可以在JavaScript中使用beforeunload事件。

使用JavaScript,你可以这样做:

window.onbeforeunload = function() {
  localStorage.removeItem(key);
  return '';
};

这将在浏览器窗口/选项卡关闭之前删除键,并提示您确认关闭窗口/选项卡操作。我希望这能解决你的问题。

注意:onbeforeunload方法应该返回一个字符串。


下面是一个简单的测试,看看你在使用本地存储时是否有浏览器支持:

if(typeof(Storage)!=="undefined") {
  console.log("localStorage and sessionStorage support!");
  console.log("About to save:");
  console.log(localStorage);
  localStorage["somekey"] = 'hello';
  console.log("Key saved:");
  console.log(localStorage);
  localStorage.removeItem("somekey");  //<--- key deleted here
  console.log("key deleted:");
  console.log(localStorage);
  console.log("DONE ===");
} else {
  console.log("Sorry! No web storage support..");
}

它为我工作如预期(我使用谷歌Chrome)。 改编自:http://www.w3schools.com/html/html5_webstorage.asp。


我不认为这里提出的解决方案是100%正确的,因为窗口。onbeforeunload事件不仅在浏览器/选项卡关闭时被调用(这是必需的),而且在所有其他几个事件上也被调用。(可能不需要)

有关可以触发window.onbeforeunload的事件列表的更多信息,请参阅此链接

http://msdn.microsoft.com/en-us/library/ms536907 (VS.85) . aspx


如果您希望在浏览器关闭时删除键,则应该使用sessionStorage。


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?

sessionStorage对象等同于localStorage对象,只是它只存储一个会话的数据。当用户关闭浏览器窗口时,数据将被删除。”

http://www.w3schools.com/html/html5_webstorage.asp


sessionStorage使用

sessionStorage对象与localStorage对象相同,只是它只存储一个会话的数据。当用户关闭浏览器窗口时,数据将被删除。

下面的例子统计用户在当前会话中点击按钮的次数:

例子

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

与window global关键字一起使用:-

 window.localStorage.removeItem('keyName');

虽然有些用户已经回答了这个问题,但我将给出一个应用程序设置示例来解决这个问题。

我也有同样的问题。我在我的angularjs应用程序中使用https://github.com/grevory/angular-local-storage模块。如果你这样配置你的应用程序,它会把变量保存在会话存储中,而不是本地存储。因此,如果您关闭浏览器或关闭选项卡,会话存储将自动删除。你什么都不需要做。

app.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
  .setPrefix('myApp')
  .setStorageType('sessionStorage')
});

希望能有所帮助。


for (let i = 0; i < localStorage.length; i++) {
    if (localStorage.key(i).indexOf('the-name-to-delete') > -1) {
        arr.push(localStorage.key(i));
    }
}

for (let i = 0; i < arr.length; i++) {
    localStorage.removeItem(arr[i]);
}

在这个问题被提出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


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

如果您希望存储身份验证或任何敏感信息,这些信息仅在浏览器关闭时被销毁,那么您可以依赖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/


没有这样的方法来检测浏览器关闭,所以可能你不能在浏览器关闭时删除localStorage,但有另一种方法来处理你可以使用sessionCookies,因为它会在浏览器关闭后销毁。这是我在我的项目中实现的。


localStorage.removeItem(key);  //item

localStorage.clear(); //all items

您可以简单地使用sessionStorage。因为sessionStorage允许在浏览器窗口关闭时清除所有键值。

看这里:SessionStorage- MDN


有五种方法可供选择:

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

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

window.localStorage.clear();

8.5年过去了,最初的问题一直没有得到答案。

当浏览器关闭时,没有一个标签。

这个基本代码片段将为您提供两全其美的服务。仅在浏览器会话期间存在的存储(如sessionStorage),但也可以在选项卡之间共享(localStorage)。

它完全通过localStorage来实现这一点。

function cleanup(){
    // place whatever cleanup logic you want here, for example:
    // window.localStorage.removeItem('my-item')
}

function tabOpened(){
    const tabs = JSON.parse(window.localStorage.getItem('tabs'))
    if (tabs === null) {
        window.localStorage.setItem('tabs', 1)
    } else {
        window.localStorage.setItem('tabs', ++tabs)
    }
}

function tabClosed(){
    const tabs = JSON.parse(window.localStorage.getItem('tabs'))
    if (tabs === 1) {
        // last tab closed, perform cleanup.
        window.localStorage.removeItem('tabs')
        cleanup()
    } else {
        window.localStorage.setItem('tabs', --tabs)
    }
}

window.onload = function () {
    tabOpened();
}

window.onbeforeunload = function () {
    tabClosed();
}


    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');

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 ; ?>";
}

这将对对象起作用。

localStorage.removeItem('key');

Or

localStorage.setItem('key', 0 );