JavaScript localStorage
back to javascript
The local storage mechanism is part of the browser Web Storage (wikipedia.org) standard.
I find it indispensable for persisting data when no server-side storage mechanism is available or reading/writing from a server would be inefficient.
window.localStorage
or just localStorage
has a very simple API.
The only real drawback is that it only stores string data. But since
any data can be encoded as a string, this isn’t a show-stopper unless
you’re doing something pretty unusual.
Here’s an entire example:
// Save localStorage.setItem("foo", "Hello World"); // Load var foo = localStorage.getItem("foo"); // foo = "Hello World" // Clear all localStorage.clear();
I also have a simple test page you can try out: localstorage.html
localStorage and local (file://) HTML files
I’ll simply quote MDN:
"For documents loaded from file: URLs (that is, files opened in the browser directly from the user’s local filesystem, rather than being served from a web server) the requirements for localStorage behavior are undefined and may vary among different browsers.
"In all current browsers, localStorage seems to return a different object for each file: URL. In other words, each file: URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn’t rely on it because, as mentioned above, the requirements for file: URLs remain undefined. So it’s possible that browsers may change their file: URL handling for localStorage at any time. In fact some browsers have changed their handling for it over time."
From Window: localStorage property (developer.mozilla.org).
That definitely matches my experience.
But all I can say for certain is that localStorage
absolutely works
for local files opened with file://
in Firefox and I’m hoping that
will continue to be the case.