javascriptsessionstorage

How to prevent sessionStorage being inherited when using target="_blank"/window.open() to open a new window/tab?


On a tab with url http://foo.com/ I set a sessionStorage item thus-

sessionStorage.bar="hello";

I then open a new window on any path on the same domain -

window.open("http://foo.com/any/path");

Then on the new window I find that -

sessionStorage.bar === "hello"

Is true. The exact same thing happens if I use a link with target="_blank" attribute to open the new window. The exact same thing also happens when a new tab is opened, and not a new window. Another thing to note is that this is only true for items set on sessionStorage before opening the new window. Adding or changing any item on sessionStorage in either windows after the new window is opened does not effect the other window in any way.

I thought that sessionStorage was supposed to be scoped to a single tab/window, but apparently sessionStorage is extended to new tabs and windows when they are opened from another window.

Is there a way to prevent this? I can probably test for existence of window.opener to detect such a case, but it would be much cleaner if it was possible to prevent it in the first place.

Thanks!


Solution

  • According to the Webstorage Specification, "When a new Document is created in a browsing context which has a top-level browsing context, the user agent must check to see if that top-level browsing context has a session storage area for that document's origin. If it does, then that is the Document's assigned session storage area."

    So, my take on this is that if you close the tab, then open a new tab, it will be a new "session" per the specification. However, if the tab remains open and you then open a new tab, the top-level browsing context matches, so the sessionStorage is referenced.