This question already has an answer here:
- Communication between tabs or windows 8 answers
I have some values in my site which i want to clear when browser is close, i chose sessionStorage to store that values, it clear when tab is close and keep storing if user press f5, but if user open some link in different tab this values unavailable. How i can share sessionStorage values between all browser tabs with my application?
The use case: put value in some storage, keep that value accessible in all browser tabs and clear it if all tabs is closed.
if (!sessionStorage.getItem(key)) {
sessionStorage.setItem(key, defaultValue)
}
My solution to not having sessionStorage transferable over tabs was to create a localProfile and bang off this variable. If this variable is set but my sessionStorage variables arent go ahead and reinitialize them. When user logs out window closes destroy this localStorage variable
Here is a solution to prevent session shearing between browser tabs for a java application. This will work for IE (JSP/Servlet)
1)first page JS
2)common JS for all pages
3)web.xml - servlet mapping
4)servlet code
You can just use
localStorage
and remember the date it was first created insession cookie
. WhenlocalStorage
"session" is older than the value of cookie then you may clear thelocalStorage
Cons of this is that someone can still read the data after the browser is closed so it's not a good solution if your data is private and confidental.
You can store your data to
localStorage
for a couple of seconds and add event listener for astorage
event. This way you will know when any of the tabs wrote something to thelocalStorage
and you can copy its content to thesessionStorage
, then just clear thelocalStorage
Actually looking at other areas, if you open with _blank it keeps the sessionStorage as long as you're opening the tab when the parent is open:
In this link, there's a good jsfiddle to test it. sessionStorage on new window isn't empty, when following a link with target="_blank"
Using
sessionStorage
for this is not possible.From the MDN Docs
That means that you can't share between tabs, for this you should use
localStorage
You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.
This code would need to exist on ALL tabs. It should execute before your other scripts.
I tested this in chrome, ff, safari, ie 11, ie 10, ie9
This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)
Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/