JavaScript > Browser APIs > Web Storage > Storage events
Web Storage and Storage Events Demo
This example demonstrates how to use Web Storage (localStorage) and listen for storage events in JavaScript. It shows how changes in one tab or window using the same origin can trigger updates in other tabs or windows.
Introduction to Web Storage
Web Storage provides a way for web pages to store data locally within the user's browser. It offers two mechanisms: localStorage
and sessionStorage
. localStorage
persists data even after the browser is closed and reopened, while sessionStorage
only lasts for the duration of the user's browser session. This example focuses on localStorage
and how to react to changes made to it from other browsing contexts using Storage Events.
Setting up the HTML
This is a basic HTML setup. An input field (myValue
), a button (saveButton
), and a div (display
) are used. The JavaScript code in script.js
will handle saving data to localStorage
and displaying its value, as well as listening for storage events.
<!DOCTYPE html>
<html>
<head>
<title>Web Storage and Storage Events</title>
</head>
<body>
<h1>Web Storage Demo</h1>
<label for="myValue">Enter a value:</label>
<input type="text" id="myValue">
<button id="saveButton">Save</button>
<div id="display"></div>
<script src="script.js"></script>
</body>
</html>
JavaScript Code for Saving Data and Listening for Storage Events
This JavaScript code does the following:
displayValue
function to retrieve the value from localStorage
and display it.localStorage
using the key 'myKey'
.storage
event listener to the window
. This event fires whenever localStorage
is modified in a different browsing context (e.g., another tab or window) sharing the same origin. The event object contains information about the change, including the key that was modified.'myKey'
, then the displayValue
function is called to update the displayed value.
// Get references to HTML elements
const myValueInput = document.getElementById('myValue');
const saveButton = document.getElementById('saveButton');
const displayDiv = document.getElementById('display');
// Function to display the current value from localStorage
function displayValue() {
const value = localStorage.getItem('myKey');
displayDiv.textContent = `Value in localStorage: ${value || 'No value stored'}`;
}
// Initial display of the value
displayValue();
// Event listener for the save button
saveButton.addEventListener('click', () => {
const value = myValueInput.value;
localStorage.setItem('myKey', value);
displayValue(); // Update display immediately in the current tab
});
// Event listener for the storage event
window.addEventListener('storage', (event) => {
if (event.key === 'myKey') {
displayValue(); // Update display when localStorage changes in another tab
}
});
Concepts Behind the Snippet
This snippet demonstrates the following concepts:
localStorage
): Storing key-value pairs in the browser's local storage.localStorage
in other browser contexts.window
object.
Real-Life Use Case
A real-life use case is maintaining user preferences across multiple tabs or windows. For example, if a user changes their theme settings in one tab, the other tabs can automatically update to reflect the new theme. This can also be used for simple cross-tab communication or synchronization of state in web applications.
Best Practices
localStorage
are unique to avoid conflicts.localStorage
has a limited storage capacity (typically around 5MB). Avoid storing large amounts of data.localStorage
.
Interview Tip
When asked about Web Storage, be prepared to discuss the differences between localStorage
and sessionStorage
, their use cases, limitations, and security considerations. Explain how storage events can be used to synchronize data across multiple tabs or windows.
When to Use Them
localStorage
when you need to persist data across browser sessions.sessionStorage
when you only need to store data for the duration of the current session.
Memory Footprint
localStorage
data persists on the user's device and contributes to the browser's storage usage. Be mindful of the amount of data you store to avoid impacting browser performance or exceeding storage quotas. Monitor the amount of storage used, especially if you are storing complex or large data structures.
Alternatives
Alternatives to Web Storage include:
Pros
localStorage
): Data remains available even after the browser is closed.
Cons
localStorage
is synchronous, which can potentially block the main thread if large amounts of data are being read or written.
FAQ
-
Why doesn't the storage event fire in the same tab that modified the localStorage?
The storage event is designed to notify other browser contexts (e.g., other tabs or windows) when localStorage is modified. It doesn't fire in the same tab because that tab is already aware of the changes it made. -
What happens if the localStorage quota is exceeded?
If the localStorage quota is exceeded, thesetItem()
method will throw an error. You should handle this error gracefully to prevent your application from crashing. You can also use thenavigator.storage.estimate()
API to check the available storage space. -
Is `localStorage` secure?
`localStorage` is not inherently secure. Data stored in `localStorage` can be accessed by any script running on the same origin. Therefore, it's crucial to avoid storing sensitive information like passwords or personal details. Implement proper input validation and sanitization to prevent cross-site scripting (XSS) attacks, which could potentially steal data from `localStorage`.