happy_story
happy_story

Reputation: 1163

sessionStorage is cleared when you open a link on a new tab, but preserved when the link is opened on the same tab. Why?

I have an anchor tag with target="_blank attribute which opens an HTML page on a new tab, and that new HTML page is linked to a JS file that has the following code:

 if (sessionStorage.getItem("washerebefore") === "yes") {
     location.href = "url of my main page";
 }

 sessionStorage.setItem("washerebefore", "yes");

The idea is obviously if you click on the link, and open the new HTML page, on refresh while there, to get redirected back to the main page, and it works fine.. but only as long as the new HTML page is opened on a new tab. If I remove the target="_blank and have the page open on the same tab, it only works the first time, as the second time I click I get redirected instantly back, which means, the sessionStorage is not cleared. Why?

I read somewhere that sessionStorage is cleared only when you close the browser, but if that's the case, then why is it getting cleared when I open the link on a new tab?

UPDATE

I tried using localStorage instead, but it's still preserved despite explicitly removing the localStorage.

 if (localStorage.getItem("washerebefore") === "yes") {
     localStorage.removeItem("washerebefore")
     location.href = "url of my main page";
 }

 localStorage.setItem("washerebefore", "yes");

Why is the localStorage not removed on refresh?

Upvotes: 4

Views: 5276

Answers (1)

Laureatus
Laureatus

Reputation: 77

Everything saved in sessionStorage gets deleted when you start a new session. A session ends when the browser is closed. The session remains when the page is reloaded. A new session gets created when a new tab is opened and that's why this bug occurs.

Upvotes: 2

Related Questions