简体   繁体   English

如何在浏览器刷新时清除会话存储,但这不应该在单击浏览器后退按钮时清除

[英]How to clear the sessionstorage on browser refresh , but this should not clear on click of browser back button

I want to clear the session storage only on page refresh but not on the browser back button click, or forward click want to implement this using angularjs/javascript我只想在页面刷新时清除 session 存储,而不是在浏览器后退按钮单击或向前单击时想使用 angularjs/javascript 来实现

i am saving data in sessionstorage on click of back button so just i want to clear the same data on click of browser refresh button but it should not clear for back我在单击后退按钮时将数据保存在会话存储中,所以我只想在单击浏览器刷新按钮时清除相同的数据,但它不应该清除后退

i have tried我努力了

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

Yes you can achieve this on windows load and then clear the session storage or removing the key 是的,您可以在Windows加载上实现此功能,然后清除会话存储或删除密钥

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

OR 要么

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

You keep the page address that set the sessionStorage and then check it on the onload event. 保留设置sessionStorage的页面地址,然后在onload事件上检查它。 If they are the same, erase the sessionStorage contents. 如果它们相同,则删除sessionStorage内容。

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

Then in the onload event: 然后在onload事件中:

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

Try to use $stateChangeStart event 尝试使用$stateChangeStart事件

$rootScope.$on('$stateChangeStart', function(event, toState, fromState){  
   if(toState.name === fromState.name){
     $window.sessionStorage.clear();
   }
})

Hope this will help!! 希望这会有所帮助!!

You can use beforeunload你可以使用 beforeunload

window.addEventListener("beforeunload", function(e) {
  sessionStorage.removeItem("{session}");
}); 

or set it as null或者设置为 null

window.addEventListener("beforeunload", function(e) {
  sessionStorage.setItem("{session}",null);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM