Localforage Introduction
Project Address Github.com/localforage/localforage
API Chinese Address localforage.docschina.org/
Speaking of local storage The first thing we think about is localstorage storage, and many people have used it, but Localstorage has the following drawbacks:
- Storage capacity limit, most browsers should be up to 5M.
- Only strings are supported, and if objects are stored, conversions are required using the Json.stringify and Json.parse methods
- Reads are synchronous, most of the time, but if the stored data is larger, the column is to store a large picture of the Base64 format, and reread may perceive delay
Loaclforage's role is to avoid the shortcomings of the above localstorage, while retaining the advantages of localstorage design.
The advantage of Localforage is that the API is very simple and easy to use, so the usage of the two is almost the same
Localforage logic is: priority to use INDEXDB to store data, if the browser does not support the use of websql, if not supported, using Localstorage
Localforage provides a callback API that also supports the ES6 Promises API, which you can choose for yourself.
Installation
You can use the NPM install Localforage or the Bower install Localforage
GetItem (Key, Successcallback)
Gets the value corresponding to the key from the warehouse and provides the result to the callback function. If key does not exist, GetItem () will return null.
GetItem () also returns NULL when the undefined is stored. Undefined cannot be stored because of Localstorage limitations and for compatibility reasons Localforage.
localforage.getitem (' Somekey '). Then (function // When the value in the offline warehouse is loaded, the code here runs Console.log (value);}). catch (function (err) { // Console.log (err);}); // callback version: localforage.getitem (' Somekey ', function (err, value) { // Console.log (value);});
SetItem (key, value, Successcallback)
Save the data to an offline warehouse. 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 as the backend, binary data is serialized before it is saved (and retrieved). When you save binary data, serialization causes the size to increase.
Localforage.setitem (' Somekey ', ' some value '). Then (function(value) {//after the value is stored, other actions can be performedConsole.log (value);}).Catch(function(err) {//When an error occurs, the code here runsConsole.log (err);});//Unlike Localstorage, you can store non-string typesLocalforage.setitem (' My Array ', [1, 2, ' three ']). Then (function(value) {//output ' 1 ' as followsConsole.log (value[0]);}).Catch(function(err) {//When an error occurs, the code here runsConsole.log (err);});//you can even store the binary data returned by the AJAX responsereq =NewXMLHttpRequest (); Req.open (' GET ', '/photo.jpg ',true); Req.responsetype= ' Arraybuffer '; Req.addeventlistener (' ReadyStateChange ',function() { if(Req.readystate = = 4) {//ReadyState completedLocalforage.setitem (' photo ', req.response). Then (function(image) {//The following is a valid tagged blob URI varBlob =NewBlob ([image]); varImageuri =window. Url.createobjecturl (BLOB); }).Catch(function(err) {//When an error occurs, the code here runsConsole.log (ERR); }); }});
RemoveItem (Key, Successcallback)
Deletes the value corresponding to the key from the offline repository.
Localforage.removeitem (' Somekey '). Then (function() { // ) when the value is removed, the code here runs Console.log (' Key is cleared! ' );}). Catch (function(err) { /// When an error occurs, the code here runs console.log (err);});
Clear (Successcallback)
Remove all keys from the database and reset the database.
Localforage.clear () will delete all values in the offline warehouse. Use this method with caution.
Localforage.clear (). Then (function() { /// when the database is completely deleted, the code here runs Console.log (' Database is now empty. ') );}). Catch (function(err) { /// When an error occurs, the code here runs console.log (err);});
Length (Successcallback)
Gets the number of keys in the offline warehouse (that is, the "length" of the Data Warehouse).
Localforage.length (). Then (function(numberofkeys) { // output Database size Console.log (Numberofkeys);}). Catch (function(err) { /// When an error occurs, the code here runs console.log (err);});
Key (KeyIndex, Successcallback)
Get its name according to the index of key
Localforage.key (2). Then (function(keyName) { // Key name Console.log ( KeyName);}). Catch (function(err) { /// When an error occurs, the code here runs console.log (err);});
Keys (Successcallback)
Get all keys in the Data Warehouse
Localforage.keys (). Then (function(keys) { // array containing all key names Console.log (keys);}). Catch (function(err) { /// When an error occurs, the code here runs console.log (err);});
Setdriver (drivername)
Setdriver ([DriverName, Nextdrivername])
If available, forces a specific driver to be set
By default, Localforage selects the back-end driver for the data warehouse in the following order:
- IndexedDB
- Websql
- Localstorage
If you want to enforce the use of a specific driver, you can use one setDriver()
or more of the following parameters:
localforage.INDEXEDDB
localforage.WEBSQL
localforage.LOCALSTORAGE
If you try to load a back-end drive that is not available on the browser, Localforage will use one of the back-end drivers that were previously used. This means that if you try to force the Gecko browser to use Websql, it will fail and continue to use IndexedDB.
// force set Localstorage to back-end driver Localforage.setdriver (localforage. Localstorage); // lists the optional drivers, sorted by priority Localforage.setdriver ([Localforage. Websql, Localforage. INDEXEDDB]);
Config (options)
Set the Localforage option. It must be called before calling Localforage, but can be called after Localforage is loaded. Any configuration values set with this method are retained, even after the driver changes, so you can call them config()
again first setDriver()
. The following configuration values can be set:
Driver
The preferred driver to use. The value format is the same as the setdriver above.
Default value: [Localforage. INDEXEDDB, Localforage. Websql, Localforage. Localstorage]
Name
The name of the database. May appear in a hint in the database. Generally use the name of your application. In Localstorage, it is used as a prefix for all keys stored in the localstorage.
Default value:'localforage'
Size
The size, in bytes, of the database. Now only for Websql
Default value: 4980736
StoreName
The name of the Data Warehouse. For DataStore in IndexedDB, the name of the database Key/value key-value table in Websql. Contains only letters and numbers and underscores. Any non-alphabetic and numeric characters are converted to underscores.
Default value:'keyvaluepairs'
Version
The version of the database. Can be used to upgrade in the future; Not currently used.
Default Value: 1.0
Description
The description of the database is generally provided to the developer.
Default value: '
// Rename the database from "Localforage" to "hipster PDA App" localforage.config ({ ' hipster PDA App '}); // the use of localstorage as a storage driver is enforced, even if other drivers are available. // available configuration instead of ' Setdriver () '. localforage.config ({ driver:localforage. Localstorage, ' I-heart-localstorage '}); // configure different driver priorities localforage.config ({ driver: [Localforage. Websql, localforage. INDEXEDDB, localforage. Localstorage], ' Websql-rox '});
Compatibility
- Android Browser 2.1
- Blackberry 7
- Chrome 23
- Chrome for Android 32
- Firefox 18
- Firefox for Android 25
- Firefox OS 1.0
- IE (ie 8+ with localstorage)
- IE Mobile 10
- Opera (opera 10.5+ with Localstorage)
- Opera Mobile 11
- Phonegap/apache Cordova 1.2.0
- Safari 3.1 (includes Mobile Safari)
Reference Address www.zhangxinxu.com/wordpress/2018/06/js-localforage-localstorage-indexdb/