Book
Search…
localforage

localforage

文档
localForage 是一个 JavaScript 库,通过简单类似 localStorage API 的异步存储来改进你的 Web 应用程序的离线体验。它能存储多种类型的数据,而不仅仅是字符串。
localForage 有一个优雅降级策略,若浏览器不支持 IndexedDB 或 WebSQL,则使用 localStorage。在所有主流浏览器中都可用:Chrome,Firefox,IE 和 Safari(包括 Safari Mobile)。
localForage 提供回调 API 同时也支持 ES6 Promises API,你可以自行选择。

安装

使用 localForage,请 下载最新版本 或使用 npm(npm install localforage)或 bower(bower install localforage)进行安装。
然后,只需包含 JS 文件即可使用 localForage:<script src="localforage.js"></script>。你不需要运行任何初始化方法或等待 onready 事件。
1
# 通过 npm 安装:
2
npm install localforage
3
4
# 或通过 bower:
5
bower install localforage
6
<script src="localforage.js"></script>
7
<script>console.log('localforage is: ', localforage);</script>
Copied!

API

localForage

Offline storage, improved.
1
// Set a value with localStorage:
2
localStorage.setItem('key', JSON.stringify('value'));
3
doSomethingElse();
4
5
// The same code with localForage:
6
localforage.setItem('key', 'value').then(doSomethingElse);
7
8
// localForage also support callbacks:
9
localforage.setItem('key', 'value', doSomethingElse);
Copied!
localForage is a JavaScript library that improves the offline experience of your web app by using an asynchronous data store with a simple, localStorage-like API. It allows developers to store many types of data instead of just strings.
localForage includes a localStorage-backed fallback store for browsers with no IndexedDB or WebSQL support. Asynchronous storage is available in the current versions of all major browsers: Chrome, Firefox, IE, and Safari (including Safari Mobile).
localForage offers a callback API as well as support for the ES6 Promises API, so you can use whichever you prefer.

Installation

1
# Install via npm:
2
npm install localforage
3
4
# Or with bower:
5
bower install localforage
Copied!
1
<script src="localforage.js"></script>
2
<script>console.log('localforage is: ', localforage);</script>
Copied!
To use localForage, download the latest release or install with npm (npm install localforage) or bower (bower install localforage).
Then simply include the JS file and start using localForage: <script src="localforage.js"></script>. You don't need to run any init method or wait for any onready events.

Data API

These APIs deal with getting and setting data in the offline store.

getItem

1
localforage.getItem('somekey').then(function(value) {
2
// This code runs once the value has been loaded
3
// from the offline store.
4
console.log(value);
5
}).catch(function(err) {
6
// This code runs if there were any errors
7
console.log(err);
8
});
9
10
// Callback version:
11
localforage.getItem('somekey', function(err, value) {
12
// Run this code once the value has been
13
// loaded from the offline store.
14
console.log(value);
15
});
Copied!
getItem(key, successCallback)
Gets an item from the storage library and supplies the result to a callback. If the key does not exist, getItem() will return null.
Even if `undefined` is saved, `null` will be returned by `getItem()`. This is due to a [limitation in localStorage](https://github.com/mozilla/localForage/pull/42), and for compatibility reasons localForage cannot store the value `undefined`.

setItem

1
localforage.setItem('somekey', 'some value').then(function (value) {
2
// Do other things once the value has been saved.
3
console.log(value);
4
}).catch(function(err) {
5
// This code runs if there were any errors
6
console.log(err);
7
});
8
9
// Unlike localStorage, you can store non-strings.
10
localforage.setItem('my array', [1, 2, 'three']).then(function(value) {
11
// This will output `1`.
12
console.log(value[0]);
13
}).catch(function(err) {
14
// This code runs if there were any errors
15
console.log(err);
16
});
17
18
// You can even store binary data from an AJAX request.
19
req = new XMLHttpRequest();
20
req.open('GET', '/photo.jpg', true);
21
req.responseType = 'arraybuffer';
22
23
req.addEventListener('readystatechange', function() {
24
if (req.readyState === 4) { // readyState DONE
25
localforage.setItem('photo', req.response).then(function(image) {
26
// This will be a valid blob URI for an <img> tag.
27
var blob = new Blob([image]);
28
var imageURI = window.URL.createObjectURL(blob);
29
}).catch(function(err) {
30
// This code runs if there were any errors
31
console.log(err);
32
});
33
}
34
});
Copied!
setItem(key, value, successCallback)
Saves data to an offline store. You can store the following types of JavaScript objects:
  • Array
  • ArrayBuffer
  • Blob
  • Float32Array
  • Float64Array
  • Int8Array
  • Int16Array
  • Int32Array
  • Number
  • Object
  • Uint8Array
  • Uint8ClampedArray
  • Uint16Array
  • Uint32Array
  • String
When using localStorage and WebSQL backends, binary data will be serialized before being saved (and retrieved). This serialization will incur a size increase when binary data is saved.
Live demo

removeItem

1
localforage.removeItem('somekey').then(function() {
2
// Run this code once the key has been removed.
3
console.log('Key is cleared!');
4
}).catch(function(err) {
5
// This code runs if there were any errors
6
console.log(err);
7
});
Copied!
removeItem(key, successCallback)
Removes the value of a key from the offline store.
Live demo

clear

1
localforage.clear().then(function() {
2
// Run this code once the database has been entirely deleted.
3
console.log('Database is now empty.');
4
}).catch(function(err) {
5
// This code runs if there were any errors
6
console.log(err);
7
});
Copied!
clear(successCallback)
Removes every key from the database, returning it to a blank slate.
`localforage.clear()` will remove **every item in the offline store**. Use this method with caution.

length

1
localforage.length().then(function(numberOfKeys) {
2
// Outputs the length of the database.
3
console.log(numberOfKeys);
4
}).catch(function(err) {
5
// This code runs if there were any errors
6
console.log(err);
7
});
Copied!
length(successCallback)
Gets the number of keys in the offline store (i.e. its "length").

key

1
localforage.key(2).then(function(keyName) {
2
// Name of the key.
3
console.log(keyName);
4
}).catch(function(err) {
5
// This code runs if there were any errors
6
console.log(err);
7
});
Copied!
key(keyIndex, successCallback)
Get the name of a key based on its ID.
This method is inherited from the localStorage API, but is acknowledged to be kinda weird.

keys

1
localforage.keys().then(function(keys) {
2
// An array of all the key names.
3
console.log(keys);
4
}).catch(function(err) {
5
// This code runs if there were any errors
6
console.log(err);
7
});
Copied!
keys(successCallback)
Get the list of all keys in the datastore.

iterate

1
// The same code, but using ES6 Promises.
2
localforage.iterate(function(value, key, iterationNumber) {
3
// Resulting key/value pair -- this callback
4
// will be executed for every item in the
5
// database.
6
console.log([key, value]);
7
}).then(function() {
8
console.log('Iteration has completed');
9
}).catch(function(err) {
10
// This code runs if there were any errors
11
console.log(err);
12
});
13
14
// Exit the iteration early:
15
localforage.iterate(function(value, key, iterationNumber) {
16
if (iterationNumber < 3) {
17
console.log([key, value]);
18
} else {
19
return [key, value];
20
}
21
}).then(function(result) {
22
console.log('Iteration has completed, last iterated pair:');
23
console.log(result);
24
}).catch(function(err) {
25
// This code runs if there were any errors
26
console.log(err);
27
});
Copied!
iterate(iteratorCallback, successCallback)
Iterate over all value/key pairs in datastore.
iteratorCallback is called once for each pair, with the following arguments:
  1. 1.
    value
  2. 2.
    key
  3. 3.
    iterationNumber - one-based number
iterate supports early exit by returning non `undefined` value inside `iteratorCallback` callback. Resulting value will be passed to `successCallback` as the result of iteration. This means if you're using CoffeeScript, you'll need to manually `return` nothing to keep iterating through each key/value pair.

Settings API

These methods allow driver selection and database configuration. These methods should generally be called before the first data API call to localForage (i.e. before you call getItem() or length(), etc.)

setDriver

1
// Force localStorage to be the backend driver.
2
localforage.setDriver(localforage.LOCALSTORAGE);
3
4
// Supply a list of drivers, in order of preference.
5
localforage.setDriver([localforage.WEBSQL, localforage.INDEXEDDB]);
Copied!
setDriver(driverName) setDriver([driverName, nextDriverName])
Force usage of a particular driver or drivers, if available.
By default, localForage selects backend drivers for the datastore in this order:
  1. 1.
    IndexedDB
  2. 2.
    WebSQL
  3. 3.
    localStorage
If you would like to force usage of a particular driver you can use setDriver() with one or more of the following arguments:
  • localforage.INDEXEDDB
  • localforage.WEBSQL
  • localforage.LOCALSTORAGE
If the backend you're trying to load isn't available on the user's browser, localForage will continue to use whatever backend driver it was previously using. This means that if you try to force a Gecko browser to use WebSQL, it will fail and continue using IndexedDB.

config

1
// This will rename the database from "localforage"
2
// to "Hipster PDA App".
3
localforage.config({
4
name: 'Hipster PDA App'
5
});
6
7
// This will force localStorage as the storage
8
// driver even if another is available. You can
9
// use this instead of `setDriver()`.
10
localforage.config({
11
driver: localforage.LOCALSTORAGE,
12
name: 'I-heart-localStorage'
13
});
14
15
// This will use a different driver order.
16
localforage.config({
17
driver: [localforage.WEBSQL,
18
localforage.INDEXEDDB,
19
localforage.LOCALSTORAGE],
20
name: 'WebSQL-Rox'
21
});
Copied!
config(options)
Set and persist localForage options. This must be called before any other calls to localForage are made, but can be called after localForage is loaded. If you set any config values with this method they will persist after driver changes, so you can call config() then setDriver(). The following config values can be set:
driver The preferred driver(s) to use. Same format as what is passed to setDriver, above. Default: [localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE]name The name of the database. May appear during storage limit prompts. Useful to use the name of your app here. In localStorage, this is used as a key prefix for all keys stored in localStorage. Default: 'localforage'size The size of the database in bytes. Used only in WebSQL for now. Default: 4980736storeName The name of the datastore. In IndexedDB this is the dataStore, in WebSQL this is the name of the key/value table in the database. Must be alphanumeric, with underscores. Any non-alphanumeric characters will be converted to underscores. Default: 'keyvaluepairs'version The schema version of your database. Used only in WebSQL and IndexedDB. In WebSQL, this simply sets the version, and in IndexedDB this may trigger an onupgradeneeded event if a version upgrade is detected. If a new store is detected, localForage will ask IndexedDB to increment the version itself to manually trigger the onupgradeneeded event. As of right now, upgrade events are not customizable, but may be in the future. For drivers that do not support configuration for versioning, this value simply gets thrown away. Default: 1.0description A description of the database, essentially for developer usage. Default: ''
Unlike most of the localForage API, the config method is synchronous.

Driver API

You can write your own, custom driver for localForage since version 1.1.

defineDriver

1
// Implement the driver here.
2
var myCustomDriver = {
3
_driver: 'customDriverUniqueName',
4
_initStorage: function(options) {
5
// Custom implementation here...
6
},
7
clear: function(callback) {
8
// Custom implementation here...
9
},
10
getItem: function(key, callback) {
11
// Custom implementation here...
12
},
13
iterate: function(iteratorCallback, successCallback) {
14
// Custom implementation here...
15
},
16
key: function(n, callback) {
17
// Custom implementation here...
18
},
19
keys: function(callback) {
20
// Custom implementation here...
21
},
22
length: function(callback) {
23
// Custom implementation here...
24
},
25
removeItem: function(key, callback) {
26
// Custom implementation here...
27
},
28
setItem: function(key, value, callback) {
29
// Custom implementation here...
30
}
31
}
32
33
// Add the driver to localForage.
34
localforage.defineDriver(myCustomDriver);
Copied!
You'll want to make sure you accept a callback argument and that you pass the same arguments to callbacks as the default drivers do. You'll also want to resolve or reject promises. Check any of the default drivers for an idea of how to implement your own, custom driver.
The custom implementation may contain a _support property that is either boolean (true/false) or returns a Promise that resolves to a boolean value. If _support is omitted, then true is the default value. You can use this to make sure the browser in use supports your custom driver.
These drivers are available to every instance of localForage on the page, regardless of which instance you use to add the implementation.

driver

1
localforage.driver();
2
// "asyncStorage"
Copied!
driver()
Returns the name of the driver being used, null during the asynchronous driver initialization process (see ready for more details), or null if the asynchronous driver initialization process failed to find a usable driver.
In case that a driver fails during or right after the initialization process, then localForage will try to use the next in order driver. That is with respect to the default driver order while loading localForage or to the order the drivers were passed to `setDriver()`.

ready

1
localforage.ready().then(function() {
2
// This code runs once localforage
3
// has fully initialized the selected driver.
4
console.log(localforage.driver()); // LocalStorage
5
}).catch(function (e) {
6
console.log(e); // `No available storage method found.`
7
// One of the cases that `ready()` rejects,
8
// is when no usable storage driver is found
9
});
Copied!
Even though localForage queues up all of its data API method calls, ready() provides a way to determine whether the asynchronous driver initialization process has finished. That's useful in cases like when we want to know which driver localForage has settled down using.

supports

1
localforage.supports(localforage.INDEXEDDB);
2
// true
Copied!
supports(driverName)
Returns (boolean) whether driverName is supported by the browser.
See setDriver for default driver names.

Multiple Instances

You can create multiple instances of localForage that point to different stores. All the configuration options used by config are supported.

createInstance

1
var store = localforage.createInstance({
2
name: "nameHere"
3
});
4
5
var otherStore = localforage.createInstance({
6
name: "otherName"
7
});
8
9
// Setting the key on one of these doesn't affect the other.
10
store.setItem("key", "value");
11
otherStore.setItem("key", "value2");
Copied!
Creates a new instance of localForage and returns it. Each object contains its own database and doesn't affect other instances of localForage.

dropInstance

1
localforage.dropInstance().then(function() {
2
console.log('Dropped the store of the current instance');
3
});
4
5
localforage.dropInstance({
6
name: "otherName",
7
storeName: "otherStore"
8
}).then(function() {
9
console.log('Dropped otherStore').
10
});
11
12
localforage.dropInstance({
13
name: "otherName"
14
}).then(function() {
15
console.log('Dropped otherName database').
16
});
Copied!
When invoked with no arguments, it drops the "store" of the current instance. When invoked with an object specifying both name and storeName properties, it drops the specified "store". When invoked with an object specifying only a name property, it drops the specified "database" (and all its stores).