Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't localStorage persisting in Chrome?

I'm trying to learn how to use the localStorage js object with the following code.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function saveStuff() {
    sessionStorage.setItem('sessionKey', 'sessionValue');
    localStorage.setItem('localKey', 'localValue');
}
</script>
</head>
<body>
<button type="button" onclick="saveStuff()">Save</button>
</body>
</html>

I am aware this doesn't always work with file:/// so I'm using mongoose to serve it up. When I click the save button, the results look correct to me in Chrome's JavaScript console. However when I press refresh both the local and the session storage get cleared where I was expecting the local storage value to persist. This happens on both http://127.0.0.1/ and http://localhost/.

Does anyone know why this might be happening? In Settings, Content Settings I have selected 'Allow local data to be set (recommended)' and unticked 'Block third-party cookies and site data'. Am I missing something in my code?

(Chrome Version 23.0.1271.64 m)

like image 565
Samuel Harmer Avatar asked Nov 08 '12 16:11

Samuel Harmer


People also ask

Does localStorage expire on browser close?

localStorage is similar to sessionStorage , except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.

How long does localStorage last in browser?

LocalStorage has no expiration time, Data in the LocalStorage persist till the user manually delete it.

Does local storage persist across browsers?

Local storage persists in different tabs/windows when using the same browser on the same machine. It does not persisted across a domain.


2 Answers

Ok. Thanks must go to pimvdb on this one but here's the solution.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function saveStuff() {
    sessionStorage.setItem('sessionKey', 'sessionValue');
    localStorage.setItem('localKey', 'localValue');
}
localStorage.getItem('localKey');
sessionStorage.getItem('sessionKey');
</script>
</head>
<body>
<button type="button" onclick="saveStuff()">Save</button>
</body>
</html>

Summary seems to be that that you must attempt a read of the key in order to persist it.

Conclusion: WTF.

like image 150
Samuel Harmer Avatar answered Oct 09 '22 04:10

Samuel Harmer


<!-- Necro post I know, but maybe it helps someone else -->

I couldn't figure out why I couldn't see something in my localStorage in Dev Tools, but could see it in the console when typing localStorage. Well, if you store something with Dev Tools open, you won't see Application -> Local Storage have anything listed for your host. When I closed/reopened Dev Tools, I could see my data.

So, in conclusion, close/reopen Dev Tools.

like image 37
cmeza Avatar answered Oct 09 '22 04:10

cmeza