简体   繁体   中英

JavaScript: sessionStorage loses item

I have following JavaScript code in the Layout-Page of my ASP.NET MVC application to store a browser wide Id for an user as a cookie so I can access information in the session on server-side for the respective user.

    if (sessionStorage.getItem("TestWindowId") == null) {
        sessionStorage.setItem("TestWindowId", "@Guid.NewGuid().ToString("N")");
        $.removeCookie("Test_Cookie");
        storeWindowIdInBrowserWideCookie();
        window.location=document.URL;
    }

    if ($.cookie("Test_Cookie") !== sessionStorage.getItem("TestWindowId")) {
        $.removeCookie("Test_Cookie");
        storeWindowIdInBrowserWideCookie();
        window.location=document.URL;
    }

    function storeWindowIdInBrowserWideCookie() {
            var cookieValue = sessionStorage.getItem("TestWindowId");
            if (cookieValue != null) {
                $.cookie("Test_Cookie", cookieValue);
            }
        }

In most cases this works.

But in some random cases for some users the sessionStorage.getItem("TestWindowId") returns null on the same browser tab it was definitely set before. In those cases I lose the Id and although the connection to the user information on server-side. According to my logs the sessionStorage item was set and in a callback call within the same second the sessionStorage of the same browser tab was null again.

What can cause the sessionStorage on client-side to lose items?

Or is there a error in my logic?

UPDATE:

There was a problem in my thinking pattern. The problem is not that the sessionStorage item was deleted but that the wrong cookie value was sent with the request to the server. I opened another ticket since the question differs: Store browser window specific id in cookie

As per the docs.

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 closing window will cause session storage to expires .

So it may happen that client has closed the browser or open it in a new tab.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM