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

8

我希望只有在页面刷新时才清除会话存储,但不会在浏览器的"后退"或"前进"按钮点击时清除。我想使用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

这个问题对我来说很好,谢谢。 - JohnMathew
4个回答

7

您需要保存设置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();
    }
}

将上述代码用if (typeof window !== "undefined")包围起来。 - undefined
@AithaRanjeeth 如果这是关于单元测试的话,你应该知道默认情况下,无论是哪个全局对象,globalchrome还是window,在运行任何测试用例之前都应该进行模拟。在npmjs.org上有一些已经准备好使用的软件包。 - undefined

6

是的,您可以在Windows加载时实现此操作,然后清除会话存储或删除键。

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

OR

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

我需要把这两行代码绑定到事件或函数中吗?还是说我需要把它放在其中? - vijay ram
每当您想重新加载页面时,请返回这两行文本:nothing just these two lines。 - md-5h04I3
@vijayram,只是一个小改动,请查看。 - md-5h04I3
出现了类似于 $window.reload() 不是一个函数的错误。 - vijay ram

1

您可以使用beforeunload

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


或者将其设置为 null。
window.addEventListener("beforeunload", function(e) {
  sessionStorage.setItem("{session}",null);
});


1
尝试使用$stateChangeStart事件。
$rootScope.$on('$stateChangeStart', function(event, toState, fromState){  
   if(toState.name === fromState.name){
     $window.sessionStorage.clear();
   }
})

希望这可以帮到你!

很不幸,该应用程序没有任何路由或者他们没有使用任何UI-Router或ng-route,但我还可以尝试吗? - vijay ram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接