What the @Wallace said this is relatively correct, however what the author probably wants is "delete the storage ", when closing the last tab or window of a specific domain, then with% will not work , because for each tab / window it will be a different session (which differs from cookies ).
About sessionStorage
(not onbeforeunload
), there is no guarantee that this will work:
window.addEventListener("beforeunload", function (event) {
localStorage.removeItem('chave-que-necessita-deletar');
});
First unbeforeload
is not and never was to detect closing windows, but rather it detects the download of the page, either by reload, pagination or closing and there is no alternative or specific function to do this, as I already answered in:
Another problem you may face is also if the browser is closed prematurely, which can cause beforeunload
, for example a taskkill to occur due to any other software that prompts the user to restart the PC (type an anti-virus).
How to solve
And as I've said before, the probably most secure path currently is a timer to check if something has already expired, for example:
JavaScript timer example with localStorage
An example (I did not thoroughly test) that should work on test would look something like this:
Combined, beforeunload
, setTimeout
, Date.parse
, Date.now
and JSON.stringify
(function (w) {
var l = w.localStorage, timersStorage = {};
function realPut(key, data)
{
l.setItem(key, data);
//Atualiza dados de 5 em 5 segundos para que o temporizador fique atualizado
timersStorage[key] = setTimeout(realPut, 5000, key, data);
}
function isExpired(timer) {
var expiresIn = new Date;
expiresIn.setTime(expiresIn.getTime() + timer * 60000);
return expiresIn < Date.now();
}
//Adiciona a função putStorage globalmente
w.setStorage = function(key, value, timer) {
//Previne conflito se acaso usar duas para uma mesma chave
if (timersStorage[key]) {
clearTimeout(timersStorage[key]);
}
realPut(key, JSON.stringify({
expires: timer,
data: value
}));
};
//Adiciona a função getStorage globalmente
w.getStorage = function(key, value, timer) {
var value = l.getItem(key);
if (!value) return;
if (String(value).indexOf("expires") !== -1) {
var parsed = JSON.parse(value);
if (Date.parse(parsed.expires) < Date.now()) {
return; //Retorna undefined se já tiver expirado
}
return parsed.data;
}
return value;
};
//Deleta dados que já passaram do "prazo de validade"
var toDelete = [], toUp = [];
for (var key in l) {
var value = l.getItem(key);
if (value.indexOf("expires") !== -1) {
var parsed = JSON.parse(value);
if (isExpired(parsed.expires)) {
toDelete.push(key);
} else {
toUp.push({ key: key, value: parsed.data, expires: parsed.expires });
}
}
}
//Deleta os expirados, é necessário executar fora do primeiro loop para não conflitar
for (var i = toDelete.length - 1; i >= 0; i--) {
l.removeItem(toDelete[i]);
}
//Atualiza os que não expiraram, é necessário executar fora do primeiro loop para não conflitar
for (var i = toUp.length - 1; i >= 0; i--) {
w.setStorage(toUp[i].key, toUp[i].value, toUp[i].expires);
}
})(window);
Use should look something like:
setStorage('foo', 'bar', 10); //Expira em 10 minutos (depois da ultima janela ter sido fechada)
setStorage('nome', 'joão', 1); //Expira em 1 minuto (depois da ultima janela ter sido fechada)
//Suporta dados em "json"
setStorage('dadospessoais', {"foo": "bar"}', 2); //Expira em 2 minutos (depois da ultima janela ter sido fechada)
To get an item:
console.log(getStorage('foo'));
If it has expired it will return JSON.parse