如何在浏览器刷新时清除sessionstorage,但是单击浏览器后退按钮时不应该清除

时间:2017-05-31 08:31:44

标签: javascript angularjs

我想仅在页面刷新时清除会话存储,但不打开                            浏览器后退按钮单击或前进单击                    想用angularjs / javascript

实现这个

我正在点击后退按钮保存sessionstorage中的数据所以我想在点击浏览器刷新按钮时清除相同的数据,但它不应该清除回来

我试过了

if (performance.navigation.type == 1) {
    $window.sessionStorage.clear();
    // clearing the sessionstorage data
}

// but this one is clearing after clicking 2 times on refresh button

if (performance.navigation.type == 0) {
    $window.sessionStorage.clear();
    // clearing the sessionstorage data

}
// this one is clearing for back button as well ,
// tried onbeforeunload, onpopstate as well its not working its clearing for back button too

// please let me know how to implement this one, thanks in advance
// no jquery please

3 个答案:

答案 0 :(得分:3)

是的,您可以在Windows加载时实现此目的,然后清除会话存储或删除密钥

$window.location.reload();
sessionStorage.clear();
  

OR

// Remove saved data from sessionStorage
 $window.location.reload();    
 sessionStorage.removeItem('key');

答案 1 :(得分:2)

保留设置sessionStorage的页面地址,然后在onload事件上进行检查。如果它们相同,则删除sessionStorage内容。

window.onbeforeunload = function(){
    sessionStorage.setItem("origin", window.location.href);
}

然后在onload事件中:

window.onload = function(){
    if(window.location.href == sessionStorage.getItem("origin")){
        sessionStorage.clear();
    }
}

答案 2 :(得分:0)

尝试使用LPTSTR/LPWSTR事件

$stateChangeStart

希望这会有所帮助!!