Article
localForage — offline key/value store for browsers
localForage is a project started at Mozilla for the purpose of providing a stable, simple key/value store API on top of various offline storage options available in modern browsers: IndexedDB, WebSQL, or localStorage.
Pretty much every storage option in modern browsers has drawbacks:
- localStorage is slow, synchronous, and works only with strings.
- IndexedDB has a very verbose API, and Safari only recently started supporting it (not without bugs).
- WebSQL requires writing SQL, is non-standard and dying.
Installing localForage
localForage is available from bower:bower install localforage
. You can also download it manually.
To use it, simply include localforage.min.js
on your page. There's also localforage.nopromises.min.js
, which doesn't include Promises shim, so that you can use it if your project already includes some sort of Promises/A+ library.
Using localForage to store data
You can use localForage functions with callbacks or promises. Example with callbacks. Setting items:localforage.setItem('key', 'value', function(err, value) {
if (err)
console.error(err);
else
console.log('Set value ', value);
});
Getting items:
localforage.getItem('key', function(err, value) {
if (err)
console.error(err);
else
console.log('Got value', value);
});
Example with ES6 Promises:
localforage.setItem('key', 'value').then(function(value) {
console.log(value);
});
To remove a stored item, call removeItem
. To remove all items, call clear
.
In addition to setting, getting, and removing items, localForage can iterate over them:
localforage.iterate(function(value, key) {
console.log([key, value]);
}, function() {
console.log('finished iterating');
});
You can also get all keys by calling keys
.
Configuring localForage
UsingsetDriver
function you can bypass automatic storage detection, and use the particular backend (supported: IndexedDB, WebSQL, localStorage). You can also write your own driver (storage backend).
By calling config
you can also set the order of preference for drivers, database name, etc.