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

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

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


当前回答

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

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.";

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

使用JavaScript,你可以这样做:

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

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

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

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

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

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

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

希望能有所帮助。