Locker makes data persistence in any browser-based JavaScript application efficient and easy. This means that you don't need to worry about testing for localStorage, sessionStorage or private browsing mode. Different browsers handle these things differently, so Locker is essentially a fault-tolerant wrapper on the Window that figures out if it's contents should be persisted or not based on if the user is in private browsing mode and/or if the user has Storage support in their browser.
Want to see something added or have an issue? Put it in the issues and i'll get on it!
If you want, you can use npm to install Locker:
npm install locker.js --saveand require it is as usual
const Locker = require('../source/locker.js');Alternatively, you could just include /build/locker.min.js in your project or use the latest version from NPM on unpkg in your <head> and use the class Locker directly.
First, let's make a new instance of Locker
const myAppStorage = new Locker();This will attempty to use window.localStorage, but if it's not there, it will fall back to it's own internal storage. To target window.sessionStorage look at this example:
const myAppStorage = new Locker('session');Now, let's store something
myAppStorage.store('foo', 'bar');
// => trueLocker supports anything that's JSON serializable, which means it can store dictionaries, lists, strings, numbers and booleans.
Now let's retrieve that thing we stored
const bar = myAppStorage.retrieve('foo');
// => 'bar'
const doesntExist = myAppStorage.retrieve('bar');
// => nullNow let's delete that thing we stored
myAppStorage.destroy('foo');
// => trueLastly, you can empty all the contents of storage
myAppStorage.empty();
// => trueIf you want to hack on Locker, make your changes in ./source/locker.js and then build it using:
npm run buildDon't forget to add tests in ./test/locker.js 😀
npm test