SessionStorage Browser. share between tabs?

I have some values ​​on my site that I want to clear when the browser is closed, I selected sessionStorage to save these values, it clears when the tab is closed, and continues to save if the user presses the f5 key, but if the user opens any link in another tab, these values ​​are not available. How can I share sessionStorage values ​​between all browser tabs with my application?

Use case: put the value in some storage, leave this value available on all browser tabs and clear it if all tabs are closed.

if (!sessionStorage.getItem(key)) { sessionStorage.setItem(key, defaultValue) } 
+120
javascript cross-browser session-storage
Dec 02 '13 at 10:16
source share
6 answers

You can use localStorage and its eventListener "store" to transfer sessionStorage data from one tab to another.

This code must exist on all tabs. It should be executed before your other scripts.

 // transfers sessionStorage from one tab to another var sessionStorage_transfer = function(event) { if(!event) { event = window.event; } // ie suq if(!event.newValue) return; // do nothing if no value to work with if (event.key == 'getSessionStorage') { // another tab asked for the sessionStorage -> send it localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage)); // the other tab should now have it, so we're done with it. localStorage.removeItem('sessionStorage'); // <- could do short timeout as well. } else if (event.key == 'sessionStorage' && !sessionStorage.length) { // another tab sent data <- get it var data = JSON.parse(event.newValue); for (var key in data) { sessionStorage.setItem(key, data[key]); } } }; // listen for changes to localStorage if(window.addEventListener) { window.addEventListener("storage", sessionStorage_transfer, false); } else { window.attachEvent("onstorage", sessionStorage_transfer); }; // Ask other tabs for session storage (this is ONLY to trigger event) if (!sessionStorage.length) { localStorage.setItem('getSessionStorage', 'foobar'); localStorage.removeItem('getSessionStorage', 'foobar'); }; 

I tested this in chrome, ff, safari, i.e. 11, i.e. 10, ie9

This method "should work in IE8", but I could not test it, since my IE crashed every time I opened a tab ... any tab ... on any website. (good ol IE) PS: you will obviously need to enable JSON padding if you want to support IE8. :)

Credit refers to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/

+110
Sep 24 '15 at 16:47
source share

Using sessionStorage for this is not possible.

From MDN Docs

Opening a page in a new tab or window will cause a new session to be initiated.

This means that you cannot share between tabs, for this you must use localStorage

+65
Dec 02 '13 at 10:21
source share
  • You can simply use localStorage and remember the date it was first created in the session cookie . When localStorage "session" is older than the cookie value, you can clear localStorage

    The disadvantages of this are that someone can still read the data after closing the browser, so it is not a good solution if your data is confidential and confidential.

  • You can save your data to localStorage for a few seconds and add an event listener for the storage event. This way, you will find out when a tab wrote something in localStorage , and you can copy its contents to sessionStorage , and then just clear localStorage

+8
Dec 02 '13 at
source share

In fact, looking at other areas, if you open using _blank, it saves sessionStorage until you open the tab when the parent is open:

There is a good jsfiddle in this link to check this out. sessionStorage in a new window is not empty when you follow the link with target = "_blank"

+8
Mar 23 '16 at 5:11
source share

My solution to not have sessionStorage portable over tabs was to create a local file and disable this variable. If this variable is set, but my sessionStorage arent variables go ahead and reinitialize them. When the user exits from the close window, destroy this localStorage variable

0
Aug 24 '16 at 17:35
source share

Here is a solution to prevent session shift between browser tabs for a Java application. This will work for IE (JSP / Servlet)

  • On the first JSP page, the onload event triggers a servlet (ajex call) to set window.title and an event tracker in the session (only an integer variable that will be set to 0 for the first time).
  • Make sure none of the other pages set window.title
  • All pages (including the first page) add a java script to check the window title after the page has finished loading. if the title is not found, close the current page / tab (do not forget to cancel the "window.unload" function when this happens)
  • Set the window.onunload page java script event (for all pages) to capture the page refresh event, if the page has been refreshed, call the servlet to reset the event tracker.

1) JS first page

 BODY onload="javascript:initPageLoad()" function initPageLoad() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var serverResponse = xmlhttp.responseText; top.document.title=serverResponse; } }; xmlhttp.open("GET", 'data.do', true); xmlhttp.send(); } 

2) common JS for all pages

 window.onunload = function() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var serverResponse = xmlhttp.responseText; } }; xmlhttp.open("GET", 'data.do?reset=true', true); xmlhttp.send(); } var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { init(); clearInterval(readyStateCheckInterval); }}, 10); function init(){ if(document.title==""){ window.onunload=function() {}; window.open('', '_self', ''); window.close(); } } 

3) web.xml - rendering the servlet

 <servlet-mapping> <servlet-name>myAction</servlet-name> <url-pattern>/data.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>myAction</servlet-name> <servlet-class>xx.xxx.MyAction</servlet-class> </servlet> 

4) servlet code

 public class MyAction extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { Integer sessionCount = (Integer) request.getSession().getAttribute( "sessionCount"); PrintWriter out = response.getWriter(); Boolean reset = Boolean.valueOf(request.getParameter("reset")); if (reset) sessionCount = new Integer(0); else { if (sessionCount == null || sessionCount == 0) { out.println("hello Title"); sessionCount = new Integer(0); } sessionCount++; } request.getSession().setAttribute("sessionCount", sessionCount); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "private, no-store, no-cache, must- revalidate"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); } } 
-10
Jan 20 '14 at 3:49
source share



All Articles