Search code examples
javascriptangularjssession-storage

sessionStorage value becomes null in other tab in AngularJS


After Login I stored the value in session in Angular:

sessionStorage.setItem("CustomerID", JSON.stringify(CustomerID));
sessionStorage.setItem("Email", JSON.stringify(email));

Here I am fetching the session value:

var sessionvalue = sessionStorage.getItem("CustomerID");

In the other tab if I open the page then the sessionvalue becomes null. It works for the same tab.

Why does it become null in the other tab the browser?


Solution

  • According to MDN

    The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

    Source: Window.sessionStorage


    So you may need something else like window.localStorage

    Example:

    // in a-page.html
    localStorage.setItem("CustomerID", JSON.stringify(CustomerID));
    
    // in b-page.html
    var CustomerID =  localStorage.getItem("CustomerID", JSON.parse(CustomerID));