在我的应用程序中,我使用sessionStorage在客户端保存数据。我的应用程序运行良好,但我希望在浏览器窗口崩溃时实现清除sessionStorage的处理。当窗口崩溃时,如何清除sessionStorage。
发布于 2017-01-24 05:24:04
通过将下面的代码实现到我的index.html文件中,我做到了这一点:
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'));
}发布于 2017-01-23 09:37:57
不知道为什么浏览器不删除所有的sessionStogare 在重新启动,因为这显然是一个新的浏览实例.
但是,您可以在应用程序中做的是总是首先清除任何最终的残余物使用
sessionStorage.clear(); // on application restart clear any eventual residues
// Your program logic here下面是一个基本的测试示例:
jsBin演示
// 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>https://stackoverflow.com/questions/41801709
复制相似问题