Simple and powerful storage library.
- ⚡ Lightweight, only 1kb after minified and gzipped
- 🕛 Support setting expiration time, the default expiration time is zero on the next day
- 🛡 Written in TypeScript with predictable static types
- 📦 No package dependencies
Using npm or yarn
$ npm install --save useful-web-storage
$ yarn add useful-web-storage
umd
<script src="https://unpkg.com/useful-web-storage@${version}/lib/index.min.js"></script>
Add script tags in your browser and use the global variable usefulWebStorage
.
<script src="https://unpkg.com/useful-web-storage@1.0.2/lib/index.min.js"></script>
<script>
const storage = usefulWebStorage.storage;
storage.clearExpiredStorage();
storage.set('name', 'useful-web-storage', storage.permanent);
storage.get('name');
</script>
define(['useful-web-storage'], function(usefulWebStorage) {
usefulWebStorage.storage.set('name', 'useful-web-storage');
});
import { storage, session } from 'useful-web-storage';
interface IUserInfo {
name: string;
age: number;
hasPermission: boolean;
hobby: string[];
}
const userInfo: IUserInfo = {
name: 'kingmui',
age: 18,
hasPermission: true,
hobby: ['sleep', 'music'],
}
// localStorage
storage.set('userInfo', userInfo, storage.permanent);
const user = storage.get<IUserInfo>('userInfo');
// sessionStorage
storage.set('userInfo', userInfo);
session.get<IUserInfo>('userInfo');
When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.
When exp
is a number, it indicates how many days will expire. The default expiration time is zero on the next day. If you want permanent storage, please manually pass in storage.permanent
.
When the obtained value does not expire, return the value. In the TypeScript
project, you can also specify the type of the return value.
Determine storage has the key.
Set a new timeout for the stored value (not expired) based on the current time.
When passed a key name, will remove that key from the storage.
When invoked, will empty all keys out of the storage.
Only clear expired storage.
Get all the storages.
forEach the storages and call the callback function with each storage.
Check if the browser supports localstorage. If not supported, nothing will be done.
Returns an integer representing the number of data items stored in the Storage object.
Get the name of the nth key in the storage.
Permanently store constant.
Download the latest version of useful-web-storage at https://github.com/fe-useful-tools/useful-web-storage/releases
useful-web-storage is licensed under a MIT License.