A simplified
localStorageAPI that just works
Forked from https://github.com/bevacqua by Nicolás Bevacqua which is no longer maintained.
Using npm
npm install local-storage-adapter --saveThe API is a simplified way to interact with all things localStorage. Note that when localStorage is unsupported in the current browser, a fallback to an in-memory store is used transparently.
For that reason, consider that local-storage-adapter values might evaporate across page views.
If a value argument is provided, acts as ls.set. When value isn't provided, acts as ls.get.
var ls = require('local-storage-adapter');
ls('foo');
// <- null
ls('foo', 'bar');
// <- true
ls('foo');
// <- 'bar'Returns value under key in local storage. Equivalent to ls(key). Internally parses the value from JSON before returning it.
var ls = require('local-storage-adapter');
ls('foo', 'bar');
// <- true
ls.get('foo');
// <- 'bar'Persists value under key in local storage. Equivalent to ls(key, value). Internally converts the value to JSON.
Returns whether an error was thrown by the browser when trying to persist the value. Failure typically means a QuotaExceededError was thrown.
var ls = require('local-storage-adapter');
ls.set('foo', 'bar');
// <- true
ls.get('foo');
// <- 'bar'Removes key from local storage. Returns true if the property was successfully deleted, and false otherwise.
var ls = require('local-storage-adapter');
ls.set('foo', 'bar');
// <- true
ls.remove('foo');
// <- trueClears local storage.
var ls = require('local-storage-adapter');
ls.set('foo', 'bar');
ls.set('baz', 'tar');
ls.clear();Listen for changes persisted against key on other tabs. Triggers fn when a change occurs, passing the following arguments.
value: the current value forkeyin local storage, parsed from the persisted JSONold: the old value forkeyin local storage, parsed from the persisted JSONurl: the url for the tab where the modification came from
Open a page with the following snippet in multiple tabs. The storage event will trigger on all tabs except for the one that persisted the change.
var ls = require('local-storage-adapter');
ls.on('foo', storage);
ls.set('foo', 'bar');
function storage (value) {
console.log('some other tab changed "foo" to ' + value);
}Removes a listener previously attached with ls.on(key, fn).
var ls = require('local-storage-adapter');
ls.on('foo', storage);
ls.off('foo', storage);
function storage (value) {
console.log('some other tab changed "foo" to ' + value);
}MIT