What the @Wallace said this relatively correct, however what the author probably wants is to "delete Storage", when closing the last tab or window of a specific domain, then with this the sessionStorage
won’t work, for each tab/window will be a different session (which differs from cookies).
About onbeforeunload
(and not unbeforeload
), is not a guarantee that this will work:
window.addEventListener("beforeunload", function (event) {
localStorage.removeItem('chave-que-necessita-deletar');
});
First of all beforeunload
it is not and never has been to detect window closing, but rather it detects page downloading, either by Reload, paging or closing and there is no alternative or specific function to do this, as I have already replied in:
Another problem you may also face is if the browser is closed prematurely, which can do the beforeunload
, for example a taskkill 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 answered other times, the way probably most guaranteed currently is a "timer" to check if something has expired, for example:
Example Javascript timer with localStorage
An example (I have not tested in depth) that should work in testing would be something like this:
I agreed to, setTimeout
, Date.parse
, Date.now
, JSON.stringify
and JSON.parse
(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);
The use should be 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 pick up an item:
console.log(getStorage('foo'));
If it has expired it will return undefined
I wanted to use sessionStorage. The problem is that if the user opens another screen in another tab it won’t catch Session. The correct would be to use a cookie but I have no idea how to use it.
– Danilo Assis