2017-01-23 130 views
1

在我的应用程序中,我使用sessionStorage来保存客户端的数据。我的应用程序工作正常,但我想实现处理清除浏览器窗口崩溃时sessionStorage。 如何在窗口崩溃时清除sessionStorage浏览器崩溃时清除sessionStorage

+0

有趣......当浏览器崩溃 - 它保留的sessionStorage重新启动时? –

+0

是的,它确实保留了sessionStorage –

回答

0

我已经通过实施下面的代码到我的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')); 
    } 
1

不知道为什么浏览器不会删除所有sessionStogare 在重新启动因为这显然是一个新的浏览实例...

你可以在你的应用程序做什么是始终首先明确使用

sessionStorage.clear(); // on application restart clear any eventual residues 

// Your program logic here 

这里任何最终残留物是一个基本的测试例子:

jsBin demo

// 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>