问题
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!
回答1:
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.
回答2:
You can workaround the inheritance behavior by using a separate key per window (or if you have multiple keys, by applying some unique prefix to each key).
That begs the question of how to assign/retain a unique key per window. Well, SessionStorage is not empty when link opened in new tab in Internet Explorer shows that you can set the name of each window to some unique value, which is retained across reloads.
来源:https://stackoverflow.com/questions/20879714/how-to-prevent-sessionstorage-being-inherited-when-using-target-blank-window