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

u0njafvf  于 2022-10-24  发布在  Angular
关注(0)|答案(3)|浏览(207)

我想只在页面刷新时清除会话存储,而不是在浏览器的后退按钮上单击,或者向前单击想要使用angularjs/javascript实现这一点
我在点击Back按钮时将数据保存在会话存储中,所以我只想在点击浏览器刷新按钮时清除相同的数据,但不应该清除Back
我试过了

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
ego6inou

ego6inou1#

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

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

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

igetnqfo2#

保留设置会话存储的页面地址,然后在onLoad事件中检查它。如果它们相同,则擦除会话存储内容。

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

然后在onLoad事件中:

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

5sxhfpxr3#

尝试使用$stateChangeStart事件

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

希望这能有所帮助!!

相关问题