Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

localforage

localForage12.4mApache-2.01.10.0TypeScript support: included

Offline storage, improved.

indexeddb, localstorage, storage, websql

readme

localForage

Build Status NPM version Dependency Status npm jsDelivr Hits minzipped size

localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asynchronous storage (IndexedDB or WebSQL) with a simple, localStorage-like API.

localForage uses localStorage in browsers with no IndexedDB or WebSQL support. See the wiki for detailed compatibility info.

To use localForage, just drop a single JavaScript file into your page:

<script src="localforage/dist/localforage.js"></script>
<script>localforage.getItem('something', myCallback);</script>

Try the live example.

Download the latest localForage from GitHub, or install with npm:

npm install localforage

Support

Lost? Need help? Try the localForage API documentation. localForage API文档也有中文版。

If you're having trouble using the library, running the tests, or want to contribute to localForage, please look through the existing issues for your problem first before creating a new one. If you still need help, feel free to file an issue.

How to use localForage

Callbacks vs Promises

Because localForage uses async storage, it has an async API. It's otherwise exactly the same as the localStorage API.

localForage has a dual API that allows you to either use Node-style callbacks or Promises. If you are unsure which one is right for you, it's recommended to use Promises.

Here's an example of the Node-style callback form:

localforage.setItem('key', 'value', function (err) {
  // if err is non-null, we got an error
  localforage.getItem('key', function (err, value) {
    // if err is non-null, we got an error. otherwise, value is the value
  });
});

And the Promise form:

localforage.setItem('key', 'value').then(function () {
  return localforage.getItem('key');
}).then(function (value) {
  // we got our value
}).catch(function (err) {
  // we got an error
});

Or, use async/await:

try {
    const value = await localforage.getItem('somekey');
    // This code runs once the value has been loaded
    // from the offline store.
    console.log(value);
} catch (err) {
    // This code runs if there were any errors.
    console.log(err);
}

For more examples, please visit the API docs.

Storing Blobs, TypedArrays, and other JS objects

You can store any type in localForage; you aren't limited to strings like in localStorage. Even if localStorage is your storage backend, localForage automatically does JSON.parse() and JSON.stringify() when getting/setting values.

localForage supports storing all native JS objects that can be serialized to JSON, as well as ArrayBuffers, Blobs, and TypedArrays. Check the API docs for a full list of types supported by localForage.

All types are supported in every storage backend, though storage limits in localStorage make storing many large Blobs impossible.

Configuration

You can set database information with the config() method. Available options are driver, name, storeName, version, size, and description.

Example:

localforage.config({
    driver      : localforage.WEBSQL, // Force WebSQL; same as using setDriver()
    name        : 'myApp',
    version     : 1.0,
    size        : 4980736, // Size of database, in bytes. WebSQL-only for now.
    storeName   : 'keyvaluepairs', // Should be alphanumeric, with underscores.
    description : 'some description'
});

Note: you must call config() before you interact with your data. This means calling config() before using getItem(), setItem(), removeItem(), clear(), key(), keys() or length().

Multiple instances

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

var store = localforage.createInstance({
  name: "nameHere"
});

var otherStore = localforage.createInstance({
  name: "otherName"
});

// Setting the key on one of these doesn't affect the other.
store.setItem("key", "value");
otherStore.setItem("key", "value2");

RequireJS

You can use localForage with RequireJS:

define(['localforage'], function(localforage) {
    // As a callback:
    localforage.setItem('mykey', 'myvalue', console.log);

    // With a Promise:
    localforage.setItem('mykey', 'myvalue').then(console.log);
});

TypeScript

If you have the allowSyntheticDefaultImports compiler option set to true in your tsconfig.json (supported in TypeScript v1.8+), you should use:

import localForage from "localforage";

Otherwise you should use one of the following:

import * as localForage from "localforage";
// or, in case that the typescript version that you are using
// doesn't support ES6 style imports for UMD modules like localForage
import localForage = require("localforage");

Framework Support

If you use a framework listed, there's a localForage storage driver for the models in your framework so you can store data offline with localForage. We have drivers for the following frameworks:

If you have a driver you'd like listed, please open an issue to have it added to this list.

Custom Drivers

You can create your own driver if you want; see the defineDriver API docs.

There is a list of custom drivers on the wiki.

Working on localForage

You'll need node/npm and bower.

To work on localForage, you should start by forking it and installing its dependencies. Replace USERNAME with your GitHub username and run the following:

# Install bower globally if you don't have it:
npm install -g bower

# Replace USERNAME with your GitHub username:
git clone git@github.com:USERNAME/localForage.git
cd localForage
npm install
bower install

Omitting the bower dependencies will cause the tests to fail!

Running Tests

You need PhantomJS installed to run local tests. Run npm test (or, directly: grunt test). Your code must also pass the linter.

localForage is designed to run in the browser, so the tests explicitly require a browser environment. Local tests are run on a headless WebKit (using PhantomJS).

When you submit a pull request, tests will be run against all browsers that localForage supports on Travis CI using Sauce Labs.

Library Size

As of version 1.7.3 the payload added to your app is rather small. Served using gzip compression, localForage will add less than 10k to your total bundle size:

minified
`~29kB`
gzipped
`~8.8kB`
brotli'd
`~7.8kB`

License

This program is free software; it is distributed under an Apache License.


Copyright (c) 2013-2016 Mozilla (Contributors).

changelog

About this CHANGELOG

This file will include all API breakage, new features, and upgrade info in localForage's lifetime.

1.10.0

  • Avoid uncaught error in dropInstance. You can now catch errors thrown by dropInstance, see #807.

1.9.0

  • Fixed TypeScript definition for getItem. It now notes that getItem can return null, so this change may cause TypeScript code that didn't account for null values to fail. See #980.

1.8.1

  • Reverted the ESM/module field change in #940, which broke many builds. See: #979. Sorry about that! 😓

1.8.0

  • No changes to code, but added a module field in package.json for better ESM support. See: #940.

1.7.4

  • Use openKeyCursor instead of openCursor for key() retrieval. Props to @MeMark2 for the fix, and thanks to @lincolnthree and @f for additional testing!

1.7.3

  • Add .npmignore file to reduce package size when installed via npm.

1.6

  • Add dropInstance() method to localforage.
  • Improve IDB driver reliability when a connection gets closed.

[1.5.7]

  • Fix IE8 localStorage support detection.

[1.5.6]

  • Upgrade lie to 3.1.1 to work with yarn.

[1.5.5]

  • Roll back dropInstance breaking change.

[1.5.4]

  • Set null as undefined (for Edge).

[1.5.3]

  • Check whether localStorage is actually usable.

[1.5.2]

  • Prevent some unnecessary logs when calling createInstance().

[1.5.1]

  • Try to re-establish IDB connection after an InvalidStateError.
  • Added Generics to iterate() TS Typings.
  • Define custom drivers syncronously when _support isn't a function.
  • Use the custom driver API for internal drivers, which makes possible to override parts of their implementation.

1.5

  • Major storage engine change for Safari: We now use IndexedDB as the storage engine for Safari v10.1 (and above). This means that pre-existing Safari >= 10.1 users will experience "data loss" after upgrading your site from a previous version of localForage to v1.5. In fact no data is lost but the engine will change so localForage will seem empty.
    • You can use the localForage 1.4 compatibility plugin after the upgrade so that all your Safari users (both old & new) continue to use the WebSQL driver.
    • Alternativelly you can force a connection to WebSQL using localForage's config to either keep using your existing WebSQL database or migrate to IndexedDB.

1.4.2

  • Fixes #562.

1.4.1

  • Fixes #520; browserify builds work properly

1.4

  • Fixes #516; this version should always load the correct driver without that bug.

1.3

  • We now use ES6 for our source code and webpack to bundle the dist/ files.

1.2

  • Iterate through the entire database using iterate(). (#283; fixes #186)

1.1

  • Custom drivers can be created using defineDriver(). (#282; fixes #267)

1.0.3

  • config() accepts a new option: driver, so users can set the driver during config rather than using setDriver(). (#273; fixes #168)

1.0

  • It is no longer necessary to queue commands using ready() when using RequireJS. (723cc94e06)
  • setDriver now accepts an array of drivers to be used, in order of preference, instead of simply a string. The string option is still supported. (eg. now one can use setDriver(['WebSQL', 'localStorage']) instead of setDriver('WebSQL'))
  • node-style, error-first argument method signatures are used for callbacks. Promises don't use error-first method signatures; instead they supply an error to the promise's reject() function.

0.9

This release drops support for some legacy browsers, though not actually the ones you might think. localForage's new policy is to support the current version of all major browsers plus up to three versions back.

  • Add built versions without the Promises polyfill to dist/ directory. (#172)
  • Drop support for Firefox 3.5. Minimum version is now Firefox 25. (Technically, Firefox 4+ seems to work.)
  • Drop support for Chrome 31 and below. Minimum version is now Chrome 32.
  • Fix a lot of bugs. Especially in Internet Exploder.
  • Switch to Mocha tests and test on Sauce Labs.
  • Add a keys() method. (#180)
  • Check for localStorage instead of assuming it's available. (#183)

Version 0.8

  • Add support for web workers. (#144, #147).

Version 0.6.1

  • Put built versions back in dist/ directory.

Version 0.6.0

  • Add localforage.config. (#40)
  • Fix iFrame bug in WebKit. (#78)
  • Improve error handling. (#60)
  • Remove support for window.localForageConfig. (#135)

Version 0.4

  • Built versions of localForage are now in the top-level directory. (2d11c90)

Version 0.3

  • Check code quality in test suite (#124)
  • _initDriver() is called after first public API call (#119)

Version 0.2.1

  • Allow configuration of WebSQL DB size (commit)
  • Use bower for JS dependencies instead of vendor/ folder (#109)

Version 0.2.0

  • Add support for ArrayBuffer, Blob, and TypedArrays (#54, #73)

Version 0.1.1

  • Added config options to allow users to set their own database names, etc. (#100)

March 16th, 2014

March 13th, 2014

March 4th, 2014