簡體   English   中英

如何在瀏覽器刷新時清除會話存儲,但這不應該在單擊瀏覽器后退按鈕時清除

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

我只想在頁面刷新時清除 session 存儲,而不是在瀏覽器后退按鈕單擊或向前單擊時想使用 angularjs/javascript 來實現

我在單擊后退按鈕時將數據保存在會話存儲中,所以我只想在單擊瀏覽器刷新按鈕時清除相同的數據,但它不應該清除后退

我努力了

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

是的,您可以在Windows加載上實現此功能,然后清除會話存儲或刪除密鑰

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

要么

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

保留設置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();
    }
}

嘗試使用$stateChangeStart事件

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

希望這會有所幫助!!

你可以使用 beforeunload

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

或者設置為 null

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM