Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 397
vijay ram Avatar asked May 31 '17 08:05

vijay ram


People also ask

Is sessionStorage cleared on refresh?

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.

Does sessionStorage clear on tab close?

Note. The sessionStorage object stores data for only one session. (The data is deleted when the browser is closed).

When using sessionStorage data is not deleted after the browser gets closed?

The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed). Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.

Does clearing cookies Clear session storage?

Local Storage data will not get cleared even if you close the browser. Because it's stored on your browser cache in your machine. Local Storage data will only be cleared when you clear the browser cache using Control + Shift + Delete or Command + Shift + Delete (Mac)


2 Answers

Yes you can achieve this on windows load and then clear the session storage or removing the key

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

OR

// Remove saved data from sessionStorage
 $window.location.reload();    
 sessionStorage.removeItem('key');
like image 108
md-5h04I3 Avatar answered Oct 09 '22 01:10

md-5h04I3


You keep the page address that set the sessionStorage and then check it on the onload event. If they are the same, erase the sessionStorage contents.

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

Then in the onload event:

window.onload = function(){
    if(window.location.href == sessionStorage.getItem("origin")){
        sessionStorage.clear();
    }
}
like image 42
Tiramonium Avatar answered Oct 09 '22 02:10

Tiramonium