Tips for clearing the sessionstorage upon browser refresh without removing data when clicking the back button in the browser

I am looking to clear the session storage only when the page is refreshed, without affecting the browser's back button functionality. I want to achieve this using AngularJS/JavaScript.

Currently, I am storing data in sessionStorage on a back button click and would like to clear this data only when the browser refresh button is clicked, without clearing it for backward navigation.

I have attempted the following:

if (performance.navigation.type == 1) {
    $window.sessionStorage.clear();
    // clearing the sessionstorage data
}

// However, this method clears the data after clicking the refresh button twice

if (performance.navigation.type == 0) {
    $window.sessionStorage.clear();
    // clearing the sessionstorage data
}
// This approach also clears the data when going back, 
// I have tried using onbeforeunload and onpopstate but they are not working as expected 

// Any suggestions on how to implement this correctly would be appreciated,
// Thank you in advance!
// Please note that jQuery solutions are not preferred

Answer №1

Save the URL of the page that sets the sessionStorage and compare it during the onload event. If they match, delete the contents of the sessionStorage.

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

Next, in the onload event:

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

Answer №2

Achieving this task on Windows load is possible by clearing the session storage or removing the key.

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

Alternatively, you can remove saved data from sessionStorage like this:

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

Answer №3

If you want to clear session data before the page is unloaded

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

Alternatively, you can also set the session data to null

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

Answer №4

Consider utilizing the $stateChangeStart event listener in your code:

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

This tip should prove useful in solving your issue!

Answer №5

To delete data from session storage or local storage, you can use the following code:

sessionStorage.removeItem('keyname');
localStorage.removeItem('keyname');

If the above method doesn't work, you can try the following approach:

window.sessionStorage.removeItem('keyname');
window.localStorage.removeItem('keyname');
window.location.reload();

These functions are specifically designed to remove a specific key from session storage or local storage. To clear the entire storage, you can use:

sessionStorage.clear();
localStorage.clear();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for modifying CSS when a user scrolls beyond a specific div

Currently, I am working on implementing a scroll function that dynamically moves elements based on the user's scrolling behavior. The code I have written works to some extent and successfully moves the elements. However, my goal is to create a list o ...

Is it possible to use JavaScript or jQuery to sort a JSON array based on multiple criteria?

I have a JSON array containing various options for an autocomplete feature. The list looks like this: var fundList = [ //there's lots more than this { "name": "Pension Managed Fund 1" }, { "name": "Managed Property Fund 2" }, { "name": " ...

What is the proper method for writing this jQuery attribute code in WordPress?

The function in my theme file looks like this: $(document).ready(function() { $(".ajax-loader").attr("src","<?php bloginfo('template_url'); ?>/images/ajax-loader.gif"); }); When executed, the src attribute displays <?php bloginfo(& ...

Is there a way to make my modal appear only when the "New" option is clicked?

Is there a way to make my modal in VueJS open only when I click on the "New" option? <select v-model="input.des" @change="$refs.modalName.openModal()"> <option value="A">A</opt ...

Utilize JavaScript to iterate through two sets of numbers

I am currently working on a project that requires me to iterate through two continuous number ranges: 1 to 5 and 10 to 15. This is the code I'm using: var X = []; for (i = 1; i < 6; i++) { X.push(i); } for (i = 10; i < 16; i++) { X.push(i ...

React: The received value for the prop type must be a function, but it was an object

I'm stuck trying to make sense of this error message, and my online search has hit a dead end. Any insights would be greatly appreciated! Attention: Prop type validation failed - expected prop type `leoInfo` to be a function from the `prop-types` pack ...

Issue encountered: Incompatibility between Mongoose Populate and Array.push()

After reading a different post addressing the same issue, I still couldn't figure out how to implement the solution into my own scenario. The discussion revolved around the topic of node js Array.push() not working using mongoose. In my Mongoose asyn ...

Automatically trigger a Bootstrap 5.2 modal when the page loads

Currently, I've been utilizing Bootstrap in conjunction with JQuery and have a specific code snippet that displays a Modal when a page is loaded. However, with the latest version 5.2 of Bootstrap, there is a push to move away from using JQuery (which ...

Using cookies locally is smooth, but unfortunately they don't seem to function as expected on VPS

I am experiencing an issue with cookies when deploying my nodejs and angularjs 1.6.4 project from localhost to Digital Ocean droplet via Github. Although everything functions properly on localhost, the cookies do not work on the droplet. Any data saved to ...

How can specific times be disabled using Laravel-9 jQuery Timepicker?

$(document).ready(function(){ $('#time').timepicker({ timeFormat: 'h:mm a', interval: 60, minTime: '9', maxTime: '4:00pm', defaultTime: '9', startTime: '9:00', dyna ...

The auto complete feature seems to be malfunctioning as an error message is being displayed stating that iElement.autocomplete is not

I am currently attempting to create an auto complete feature for a search text box using Angularjs. However, I am encountering an error stating that iElement.autocomplete is not a function. Here is the code snippet: <body ng-controller='Friend ...

Implementing translation text into a PHP database

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Translate and Save Text</title> </head> <body> <form action="" method="post" name="theform"> <table width="693" border="1" style="table-l ...

Is it possible to notify the user directly from the route or middleware?

In my current setup, I am utilizing a route to verify the validity of a token. If the token is invalid, I redirect the user to the login page. I am considering two options for notifying users when they are being logged out: either through an alert message ...

Is it possible to utilize CSS to form a triangle outline on the right-hand side of a Bootstrap list group?

https://i.sstatic.net/vSoa0.png Hey everyone! I'm trying to achieve a triangle shape using CSS at the end of a list item. I've utilized the list group component from Bootstrap to display my list. Below is a snippet of my code. I've als ...

Encountering a persistent Unhandled rejection Error while utilizing NodeJs with Bluebird library

Currently in the process of developing a daemon that listens to TCP connections, sends commands, and listens for events. I made the decision to utilize bluebird to eliminate callbacks, but I'm encountering an issue. I can't seem to catch a rejec ...

I'm having trouble getting my accordion menu to work properly. Whenever I click on the question title, the answer doesn't seem to show up or collapse. What could be causing this issue?

I am currently working on a project to create an accordion menu where the answers are hidden and only revealed upon clicking the question. However, when I test it out, nothing happens when I click on the question. Here is my code: .accordion-Section ...

Vue.js global event issue

Recently, I encountered an issue with the following code: <component-one></component-one> <component-two></component-two> <component-three></component-three> Specifically, component-two contains component-three. My cu ...

Error in React JS: SyntaxError - "Unexpected token '?'"

Following the guidelines on this website, I successfully set up a new reactJS application, proceeded to run npm i && npm run dev and encountered the following error message: /home/www/node_modules/next/dist/cli/next-dev.js:362 showAll ...

The Ionic application is experiencing difficulties in loading the JSON file

I am currently delving into the world of Ionic development and utilizing localhost to test my app. My goal is to create a contacts list application where contact details such as name, email, phone number, and avatar are loaded from a JSON file. However, I& ...

Uncovering hidden links in a menu with Python Selenium and JavaScript

Can someone provide guidance on how to activate the JavaScript submenu associated with this button, "x-auto-54"? <table id="x-auto-54" class=" x-btn avtar-x-btn x-component x-btn-noicon x-unselectable " cellspacing="0" role="prese ...