localStorage.username = 'johnsmith001';
console.log(localStorage.username); // prints johnsmith001 to the console
delete localStorage.username;
console.log(localStorage.username); // prints undefined to the console
Some templates need to store data about the user’s session, such as a user’s name or game score.
You can store data temporarily by using window.sessionStorage
.
However, data stored in this way expires when the session ends.
If you need to persist data across sessions, use window.localStorage
.
Data stored in this way has no expiration date.
It will be available until the browser’s cache is cleared.
For example, here is a link to a Koji that uses local storage to store the user’s name: Chatbox
When you first run the Koji, your user name is set to Anonymous.
You can change it by tapping the cog icon in the top left corner.
The new name is saved to local storage.
The relevant code is in the Chatbox.js
file of the template: Chatbox.js
There are two ways to use window.localStorage
.
Use property names directly:
localStorage.username = 'johnsmith001';
console.log(localStorage.username); // prints johnsmith001 to the console
delete localStorage.username;
console.log(localStorage.username); // prints undefined to the console
Alternatively, localStorage
provides the methods setItem
and removeItem
, which you can use as follows:
localStorage.setItem('username', 'johnsmith001');
console.log(localStorage.getItem('username')); // prints johnsmith001 to the console
localStorage.removeItem('username');
console.log(localStorage.getItem('username')); // prints undefined to the console
Check that windows.localStorage
is accessible before using it.
If the user has selected Block third-party cookies and site data in the content settings of the browser, local storage will be inaccessible.
Local storage may also be inaccessible in incognito mode (private browsing).
To avoid an error in these situations, always check that local storage is available before using it.
To check whether local storage is accessible, you can use a function like this example.
function isLocalStorageAvailable() {
const test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch (e) {
return false;
}
}
If local storage is inaccessible, you can decide to persist the data for only the duration of the session or you can save it to a database, such as the built-in Koji database.