Reputation: 536
In my application I am using sessionStorage
to save data at client side. My application working fine but I want to implement a handling of clearing sessionStorage
when browser window got crashed.
How can I clear the sessionStorage
when window crashed.
Upvotes: 1
Views: 1053
Reputation: 536
I have acheived this by implementing below code into my index.html file:
window.addEventListener('load', function () {
sessionStorage.setItem('good_exit', 'pending');
setInterval(function () {
sessionStorage.setItem('time_before_crash', new Date().toString());
}, 1000);
});
window.addEventListener('beforeunload', function () {
sessionStorage.setItem('good_exit', 'true');
});
if(sessionStorage.getItem('good_exit') &&
sessionStorage.getItem('good_exit') !== 'true') {
/*
insert crash logging code here
*/
alert('Hey, welcome back from your crash, looks like you crashed on: ' + sessionStorage.getItem('time_before_crash'));
}
Upvotes: 0
Reputation: 206565
Not sure why the browser doesn't erase all sessionStogare on reboot since that's clearly a new browsing instance...
but what you could do in your application is to always firstly clear any eventual residues using
sessionStorage.clear(); // on application restart clear any eventual residues
// Your program logic here
Here's a basic test example:
// 1. let's clear it
sessionStorage.clear();
// 2. Let's try to store a value
document.querySelector("button").addEventListener("click", function(){
sessionStorage.test = "TEST";
document.body.textContent = sessionStorage.test;
});
// 3. let's try to crash Chrome (copy this into a tab addressbar)
// chrome://inducebrowsercrashforrealz
// 4. on browser RESTORE we should see the button, not the stored value
if(sessionStorage.test) document.body.textContent = sessionStorage.test;
<button>CLICK TO STORE</button>
Upvotes: 1