HTML5 local storage API (part of web storage) has excellent browser support and is being applied in more and more applications. It has a simple API, but it also has some disadvantages similar to cookies.
I have encountered quite a few tools and libraries using the localStorage API over the past year or so, so I have sorted them out into this post with some code examples and feature discussions.
Key points
Lockr
Lockr is a wrapper for the localStorage API that allows you to use many useful methods and features. For example, while localStorage is limited to storing strings, Lockr allows you to store different data types without having to convert them yourself:
Lockr.set('website', 'SitePoint'); // 字符串 Lockr.set('categories', 8); // 数字 Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]); // 对象
Other functions include:
The Local Storage Bridge
A 1KB library for using localStorage as a communication channel to facilitate message exchange between tabs in the same browser. Once the library is included, here is the sample code you can use:
// 发送消息 lsbridge.send('my-namespace', { message: 'Hello world!' }); // 监听消息 lsbridge.subscribe('my-namespace', function(data) { console.log(data); // 打印:'Hello world!' });
As shown, the send() method creates and sends messages, and the subscribe() method allows you to listen for specified messages. You can read more about the library in this blog post.
Barn
This library provides a Redis-like API that provides a "fast, atomized persistent storage layer" on top of localStorage. Below is a sample code snippet taken from the README of the repo. It demonstrates many methods available.
Lockr.set('website', 'SitePoint'); // 字符串 Lockr.set('categories', 8); // 数字 Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]); // 对象
API include the ability to use the start/end values to get ranges, get items arrays, and compress the entire data store to save space. This repo contains a complete reference to all methods and their functions.
store.js
This is another wrapper similar to Lockr, but this time it provides deeper browser support through fallback. README explains, "store.js uses localStorage when available and falls back to userData behavior in IE6 and IE7. There is no Flash to slow down page loading. There is no cookie to increase the burden on network requests."
The basic API is explained in the comments in the following code:
// 发送消息 lsbridge.send('my-namespace', { message: 'Hello world!' }); // 监听消息 lsbridge.subscribe('my-namespace', function(data) { console.log(data); // 打印:'Hello world!' });
In addition, there are some more advanced features:
var barn = new Barn(localStorage); barn.set('key', 'val'); console.log(barn.get('key')); // val barn.lpush('list', 'val1'); barn.lpush('list', 'val2'); console.log(barn.rpop('list')); // val1 console.log(barn.rpop('list')); // val2 barn.sadd('set', 'val1'); barn.sadd('set', 'val2'); barn.sadd('set', 'val3'); console.log(barn.smembers('set')); // ['val1', 'val2', 'val3'] barn.srem('set', 'val3'); console.log(barn.smembers('set')); // ['val1', 'val2']
README on GitHub repo details the depth of browser support and potential bugs and pitfalls to be considered (for example, some browsers do not allow local storage in privacy mode).
lscache
lscache is another localStorage wrapper, but with some extra features. You can use it as a simple localStorage API or use the functionality of emulating Memcached (memory object caching system).
lscache exposes the following method, which is described in the comments in the code:
// 在'website'中存储'SitePoint' store.set('website', 'SitePoint'); // 获取'website' store.get('website'); // 删除'website' store.remove('website'); // 清除所有键 store.clear();
Like the previous library, this library also handles serialization, so you can store and retrieve objects:
// 存储对象字面量;在后台使用JSON.stringify store.set('website', { name: 'SitePoint', loves: 'CSS' }); // 获取存储的对象;在后台使用JSON.parse var website = store.get('website'); console.log(website.name + ' loves ' + website.loves); // 获取所有存储的值 console.log(store.getAll()); // 循环遍历所有存储的值 store.forEach(function(key, val) { console.log(key, val); });
Finally, lscache allows you to divide data into "buckets". Check out this code:
// 设置一个带有2分钟过期时间的问候语 lscache.set('greeting', 'Hello World!', 2); // 获取并显示问候语 console.log(lscache.get('greeting')); // 删除问候语 lscache.remove('greeting'); // 刷新整个缓存项目 lscache.flush(); // 只刷新过期的项目 lscache.flushExpired();
Note that in the second log, the result is null. This is because I set up a custom bucket before logging the result. Once I set up a bucket, nothing added to lscache before this will be inaccessible, even if I try to refresh it. Only items in the "other" bucket are accessible or refreshable. Then when I reset the bucket I was able to access my original data again.
secStore.js
secStore.js is a data storage API that adds an optional security layer through the Stanford Javascript Crypto Library. secStore.js allows you to select storage methods: localStorage, sessionStorage, or cookie. To use secStore.js you must also include the sjcl.js library mentioned earlier.
The following is an example showing how to save some data with the encrypt option set to "true":
lscache.set('website', { 'name': 'SitePoint', 'category': 'CSS' }, 4); // 从对象中检索数据 console.log(lscache.get('website').name); console.log(lscache.get('website').category);
Note the set() method used, which passes in the options you specified (including custom data) and a callback function that allows you to test the results. Then, we can use the get() method to retrieve the data:
lscache.set('website', 'SitePoint', 2); console.log(lscache.get('website')); // 'SitePoint' lscache.setBucket('other'); console.log(lscache.get('website')); // null lscache.resetBucket(); console.log(lscache.get('website')); // 'SitePoint'
If you want to use sessionStorage or cookies instead of localStorage in secStore.js, you can define it in the options:
var storage = new secStore; var options = { encrypt: true, data: { key: 'data goes here' } }; storage.set(options, function(err, results) { if (err) throw err; console.log(results); });
localForage
This library built by Mozilla provides you with a simple localStorage-like API, but uses asynchronous storage via IndexedDB or WebSQL. The API is exactly the same as localStorage (getItem(), setItem(), etc.), except that its API is asynchronous and the syntax requires the use of callbacks.
So for example, you won't get the return value regardless of whether you set or get the value, but you can handle the data passed to the callback function and (optional) handle the error:
Lockr.set('website', 'SitePoint'); // 字符串 Lockr.set('categories', 8); // 数字 Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]); // 对象
Some other points about localForage:
Basil.js
Basil.js is described as a unified localStorage, sessionStorage, and cookie API, which contains some unique and very easy to use features. The basic method can be used as follows:
// 发送消息 lsbridge.send('my-namespace', { message: 'Hello world!' }); // 监听消息 lsbridge.subscribe('my-namespace', function(data) { console.log(data); // 打印:'Hello world!' });
You can also use Basil.js to test if localStorage is available:
var barn = new Barn(localStorage); barn.set('key', 'val'); console.log(barn.get('key')); // val barn.lpush('list', 'val1'); barn.lpush('list', 'val2'); console.log(barn.rpop('list')); // val1 console.log(barn.rpop('list')); // val2 barn.sadd('set', 'val1'); barn.sadd('set', 'val2'); barn.sadd('set', 'val3'); console.log(barn.smembers('set')); // ['val1', 'val2', 'val3'] barn.srem('set', 'val3'); console.log(barn.smembers('set')); // ['val1', 'val2']
Basil.js also allows you to use cookies or sessionStorage:
// 在'website'中存储'SitePoint' store.set('website', 'SitePoint'); // 获取'website' store.get('website'); // 删除'website' store.remove('website'); // 清除所有键 store.clear();
Finally, in the option object, you can use the option object to define the following:
// 存储对象字面量;在后台使用JSON.stringify store.set('website', { name: 'SitePoint', loves: 'CSS' }); // 获取存储的对象;在后台使用JSON.parse var website = store.get('website'); console.log(website.name + ' loves ' + website.loves); // 获取所有存储的值 console.log(store.getAll()); // 循环遍历所有存储的值 store.forEach(function(key, val) { console.log(key, val); });
lz-string
lz-string utility allows you to store large amounts of data in localStorage by using compression, and it is very easy to use. After including the library on the page, you can do the following:
// 设置一个带有2分钟过期时间的问候语 lscache.set('greeting', 'Hello World!', 2); // 获取并显示问候语 console.log(lscache.get('greeting')); // 删除问候语 lscache.remove('greeting'); // 刷新整个缓存项目 lscache.flush(); // 只刷新过期的项目 lscache.flushExpired();
Please pay attention to the use of compress() and decompress() methods. The comments in the above code show the length values before and after compression. You can see how beneficial this will be, as client storage is always limited in space.
As explained in the library documentation, you can choose to compress the data into Uint8Array (a newer data type in JavaScript) and even compress the data to store externally on the client.
Honorable Mentions
The above tools may help you do almost everything you want to do in localStorage, but if you are looking for more, here are some more related tools and libraries you might want to check out.
Do you know other libraries?
If you have built some tools to enhance client storage on top of the localStorage API or related tools, feel free to let us know in the comments.
(The rest of the article is FAQ, which has been rewritten and streamlined according to the original text, and the original intention is maintained)
Frequently Asked Questions about JavaScript Local Repositories (FAQ)
Q: What are the benefits of using JavaScript local repositories?
A: JavaScript local repository provides many benefits. They provide a more efficient way to store data on the client side, which can significantly improve the performance of web applications. These libraries also provide a higher level of security than traditional data storage methods, as they allow data encryption. Additionally, they provide a more user-friendly interface for data management, making it easier for developers to use local storage.
Q: How does local storage work in JavaScript?
A: Local storage in JavaScript allows web applications to persist in storing data in a web browser. Unlike cookies, local storage does not expire and is not sent back to the server, making it a more efficient method of data storage. Data stored in local storage is saved across browser sessions, meaning it is still available even if the browser is closed and reopened.
Q: Can I use local storage for sensitive data?
A: While local storage provides a convenient way to store data on the client, it is not recommended to use it for storing sensitive data. This is because local storage is not designed as a secure storage mechanism. Data stored in local storage can be easily accessed and manipulated using simple JavaScript code. Therefore, sensitive data such as passwords, credit card numbers, or personal user information should not be stored in local storage.
Q: How to manage data in local storage?
A: Managing data in local storage involves three main actions: setting up items, getting items, and deleting items. To set the project, you can use the setItem() method, which accepts two parameters: key and value. To retrieve an item, you can use the getItem() method, which accepts the key as an argument and returns the corresponding value. To delete an item, you can use the removeItem() method, which accepts a key as an argument.
Q: What are some popular local JavaScript repositories?
A: There are several popular local repositories for JavaScript, including store.js, localForage, and js-cookie. Store.js provides a simple and consistent API for local storage and runs on all major browsers. LocalForage provides a powerful asynchronous storage API and supports IndexedDB, WebSQL and localStorage. Js-cookie is a lightweight library for handling cookies that can be used as a fallback when local storage is unavailable.
Q: How to check if local storage is available?
A: You can use the simple try/catch block in JavaScript to check if local storage is available. The window.localStorage property can be used to access local storage objects. Local storage is available if this property exists and can be used to set up and retrieve items.
Q: What is the storage limit for local storage?
A: The storage limits for local storage vary from browser to browser, but are usually around 5MB. This is much larger than the storage limit of cookies (only 4KB). However, it is better to be aware of the amount of data you store in your local storage, as too much data can slow down your web applications.
Q: Can local storage be shared between different browsers?
A: No, local storage cannot be shared between different browsers. Each web browser has its own independent local storage, so the data stored in one browser will not be available in another. This is important when designing web applications that rely on local storage.
Q: How to clear all data in local storage?
A: You can use the clear() method to clear all data in the local storage. This method does not accept any parameters and will delete all items from the local storage. Be careful when using this method, as it permanently deletes all data in the local storage.
Q: Can local storage be used on mobile devices?
A: Yes, local storage can be used on mobile devices. Most modern mobile web browsers support local storage, so you can use it on desktop and mobile devices to store data. However, storage limitations on mobile devices may be low, so it is important to consider this when designing web applications.
The above is the detailed content of 9 JavaScript Libraries for Working with Local Storage. For more information, please follow other related articles on the PHP Chinese website!