2017-01-23 136 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>