我只想在页面刷新时清除会话存储,而不是在 单击浏览器后退按钮,或单击前进 想使用 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
您保留设置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();
}
}
是的,您可以在 Windows 加载上实现此目的,然后清除会话存储或删除密钥
$window.location.reload();
sessionStorage.clear();
或
// Remove saved data from sessionStorage
$window.location.reload();
sessionStorage.removeItem('key');
可以使用beforeunload
window.addEventListener("beforeunload", function(e) {
sessionStorage.removeItem("{session}");
});
或将其设置为空
window.addEventListener("beforeunload", function(e) {
sessionStorage.setItem("{session}",null);
});
尝试使用
$stateChangeStart
事件
$rootScope.$on('$stateChangeStart', function(event, toState, fromState){
if(toState.name === fromState.name){
$window.sessionStorage.clear();
}
})
希望这会有所帮助!
为了删除会话存储或本地存储,我们可以
sessionStorage.removeItem('keyname');
localStorage.removeItem('keyname');
如果这不起作用那么最好的方法是
window.sessionStorage.removeItem('keyname');
window.localStorage.removeItem('keyname');
window.location.reload();
以上所有功能均用于从会话存储或本地存储中删除特定密钥,同时我们可以使用清除整个存储
sessionStorage.clear();
localStorage.clear();