Why is sessionStorage preserved across multiple tabs?

From Window.sessionStorage docs:

Opening multiple tabs or Windows on the same URL creates sessionStorage for each tab or Window

https://stackblitz.com/edit/session-storage?file=index.js

Enter your name and click “store”

Your name is now stored in sessionStorage and page view is updated.

sessionStorage.setItem('name', nameInput.value);
nameSpan.innerHTML = nameInput.value;

Now click “open in new tab”

This will open page in new tab by creating link element to the current page, and calling click() on it

const link = document.createElement('a');
link.target = '_blank';
link.href = '/';
link.setAttribute('visibility', 'hidden');
document.body.appendChild(link);
link.click();
link.remove();

As you can see, your name is still there

Why is this happening and is there a way to make new tab open with empty sessionStorage (without clearing current tab sessionStorage)?

Tested this on Chrome 75 and Firefox 66

No, it has nothing to do with stackblitz, behaves the same way on localhost

Answer

The session has to work that way to maintain state if you navigate to another link within the same application. If you want to open a tab without that session try using incognito mode. Incognito mode will open window with fresh session.

sessionStorage on new window isn’t empty, when following a link with target=”_blank”

Leave a Reply

Your email address will not be published. Required fields are marked *