Storage Event Listener
Listen to storage changes across tabs
IntermediateTopic: LocalStorage/SessionStorage
JavaScript Storage Event Listener Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Listen to storage changes
window.addEventListener('storage', function(e) {
console.log('Storage changed');
console.log('Key:', e.key);
console.log('Old value:', e.oldValue);
console.log('New value:', e.newValue);
console.log('URL:', e.url);
// Update UI when storage changes
if (e.key === 'theme') {
document.body.className = e.newValue;
}
});
// Method 2: Custom storage event (same tab)
// Note: storage event only fires in OTHER tabs/windows
// For same tab, use custom events
function setItemWithEvent(key, value) {
const oldValue = localStorage.getItem(key);
localStorage.setItem(key, value);
// Dispatch custom event for same tab
window.dispatchEvent(new CustomEvent('localStorageChange', {
detail: { key, oldValue, newValue: value }
}));
}
window.addEventListener('localStorageChange', function(e) {
console.log('LocalStorage changed (same tab):', e.detail);
});
// Usage
setItemWithEvent('username', 'John');
// Method 3: Storage helper with events
class StorageManager {
static setItem(key, value) {
const oldValue = localStorage.getItem(key);
localStorage.setItem(key, value);
// Custom event for same tab
window.dispatchEvent(new CustomEvent('storageChange', {
detail: { key, oldValue, newValue: value, storageArea: 'localStorage' }
}));
}
static getItem(key) {
return localStorage.getItem(key);
}
static removeItem(key) {
const oldValue = localStorage.getItem(key);
localStorage.removeItem(key);
window.dispatchEvent(new CustomEvent('storageChange', {
detail: { key, oldValue, newValue: null, storageArea: 'localStorage' }
}));
}
}
// Listen to changes
window.addEventListener('storageChange', function(e) {
console.log('Storage changed:', e.detail);
});
// Use StorageManager
StorageManager.setItem('theme', 'dark');
StorageManager.setItem('language', 'en');
// Method 4: Sync data across tabs
let syncData = {
counter: 0,
lastUpdate: Date.now()
};
// Save to localStorage
localStorage.setItem('syncData', JSON.stringify(syncData));
// Listen for changes from other tabs
window.addEventListener('storage', function(e) {
if (e.key === 'syncData') {
const newData = JSON.parse(e.newValue);
console.log('Data synced from other tab:', newData);
syncData = newData;
updateUI();
}
});
function updateSyncData() {
syncData.counter++;
syncData.lastUpdate = Date.now();
localStorage.setItem('syncData', JSON.stringify(syncData));
}
function updateUI() {
console.log('Counter:', syncData.counter);
console.log('Last update:', new Date(syncData.lastUpdate));
}Output
LocalStorage changed (same tab): { key: 'username', oldValue: null, newValue: 'John' }
Storage changed: { key: 'theme', oldValue: null, newValue: 'dark', storageArea: 'localStorage' }
Storage changed: { key: 'language', oldValue: null, newValue: 'en', storageArea: 'localStorage' }
Counter: 1
Last update: 2024-01-01T12:00:00.000ZUnderstanding Storage Event Listener
Storage events enable cross-tab communication.
Storage Event
•Fires in OTHER tabs/windows
•Does NOT fire in same tab
•key: Changed key
•oldValue: Previous value
•newValue: New value
•url: Origin URL
Custom Events
•For same-tab changes
•Dispatch custom events
•Listen with addEventListener
Use Cases
•Sync data across tabs
•Update UI on changes
•Real-time collaboration
•Multi-tab apps
Best Practices
•Use custom events for same tab
•Handle storage events for other tabs
•Validate data on receive
•Update UI accordingly
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.