4.1 localStorage and sessionStorage
Web Storage lets web apps store data in the user's browser. It's handy for keeping info that should stick around between visits or while navigating pages. HTML5 introduced two main types of web storage: localStorage and sessionStorage.
What's localStorage?
localStorage is a type of data storage that saves in the user's browser indefinitely. Data in localStorage are still there even after closing the browser and rebooting the computer. It's great for keeping info that needs to persist across sessions, like user settings or shopping cart data.
What's sessionStorage?
sessionStorage is data storage that stays in the user's browser for one session. Data in sessionStorage are available only as long as the browser tab or window is open. It's useful for temporary data like form data or application states needed only for a single session.
Main Methods and Properties
Methods and Properties of localStorage and sessionStorage
Both web storage types have the same API, which includes methods and properties for working with data:
setItem(key, value)
: saves a value with the specified key.getItem(key)
: returns the value stored with the specified key.removeItem(key)
: deletes the value with the specified key.clear()
: clears all data in the storage.key(index)
: returns the key at the specified index.length
: returns the number of key-value pairs in storage.
4.2 Usage Examples
Example of using localStorage:
<!DOCTYPE html>
<html>
<head>
<title>localStorage Example</title>
</head>
<body>
<h1>localStorage Example</h1>
<input type="text" id="username" placeholder="Enter your username">
<button id="saveButton">Save</button>
<button id="loadButton">Load</button>
<script>
const saveButton = document.getElementById('saveButton');
const loadButton = document.getElementById('loadButton');
const usernameInput = document.getElementById('username');
// Saving value in localStorage
saveButton.addEventListener('click', function() {
const username = usernameInput.value;
localStorage.setItem('username', username);
alert('Username saved!');
});
// Loading value from localStorage
loadButton.addEventListener('click', function() {
const savedUsername = localStorage.getItem('username');
if (savedUsername) {
usernameInput.value = savedUsername;
alert('Username loaded!\n' + `${savedUsername}`);
} else {
alert('No username found.');
}
});
</script>
</body>
</html>
Example of using sessionStorage:
<!DOCTYPE html>
<html>
<head>
<title>sessionStorage Example</title>
</head>
<body>
<h1>sessionStorage Example</h1>
<input type="text" id="sessionData" placeholder="Enter some data">
<button id="saveSessionButton">Save</button>
<button id="loadSessionButton">Load</button>
<script>
const saveSessionButton = document.getElementById('saveSessionButton');
const loadSessionButton = document.getElementById('loadSessionButton');
const sessionDataInput = document.getElementById('sessionData');
// Saving value in sessionStorage
saveSessionButton.addEventListener('click', function() {
const data = sessionDataInput.value;
sessionStorage.setItem('data', data);
alert('Data saved in session!');
});
// Loading value from sessionStorage
loadSessionButton.addEventListener('click', function() {
const savedData = sessionStorage.getItem('data');
if (savedData) {
sessionDataInput.value = savedData;
alert('Data loaded from session!\n' + `${savedData}`);
} else {
alert('No data found in session.');
}
});
</script>
</body>
</html>
4.3 Comparing localStorage and sessionStorage
Differences between localStorage and sessionStorage
-
Storage Duration:
- localStorage keeps data indefinitely until the user or script deletes them.
- sessionStorage keeps data only for the duration of the current session (browser tab or window).
-
Scope:
- Data in localStorage are available across tabs and windows of the same domain.
- Data in sessionStorage are available only in the current tab or window.
-
Storage Size:
- Usually, localStorage and sessionStorage have a limit of 5-10 MB per domain, depending on the browser.
Example comparing localStorage and sessionStorage:
<!DOCTYPE html>
<html>
<head>
<title>Comparison Example</title>
</head>
<body>
<script>
// Using localStorage
localStorage.setItem('persistentData', 'This data persists across sessions');
console.log(localStorage.getItem('persistentData')); // "This data persists across sessions"
// Using sessionStorage
sessionStorage.setItem('temporaryData', 'This data persists only during the session');
console.log(sessionStorage.getItem('temporaryData')); // "This data persists only during the session"
</script>
</body>
</html>
4.4 Use Cases
When to use localStorage:
- Store data that should persist across sessions, like user settings or preferences
- Store data accessible in all tabs and windows of the same domain
- Store data that doesn't change often
When to use sessionStorage:
- Store temporary data needed only during the current session
- Store data specific to the current tab or window
- Data that should be deleted when the tab or window is closed
Security and Privacy
When using web storage, it's important to consider security and privacy:
- Encryption: data in web storage aren't encrypted by default. If you need to store sensitive information, it's recommended to encrypt data before storing.
- Cross-domain attacks: web storage works within a single domain, preventing data access from other domains. However, protect against XSS (cross-site scripting) attacks so intruders can't access storage data.
- Data volume limit: try to store only necessary information and regularly clear outdated data to avoid storage overflow.
GO TO FULL VERSION