Listen to localStorage changes in different windows/tabs
whenlocalStorage
When the data of changes in one window/tab, other windows/tabs of the same origin will triggerstorage
event. We can use this event to listenlocalStorage
Changes.
Sample code
// Add storage event listener('storage', function(event) { if ( === 'groupID') { ('New value:', ); } });
explain
-
storage
Events will be fired in other windows/tabs of the same origin. -
It's changing
localStorage
Key of the item. -
It is the new value after the change.
Things to note
- Only modify between different windows/tabs
localStorage
It will only triggerstorage
event. - If modified in the same window/tab
localStorage
, it will not triggerstorage
event.
Listen to localStorage changes in the same window/tab
In the same window/tab,storage
Events will not be triggered. We can achieve thelocalStorage
Change listening.
Method 1: Use custom events
- set up
localStorage
And trigger a custom event
function setLocalStorageItem(key, value) { (key, value); const event = new CustomEvent('localStorageChange', { detail: { key, value } }); (event); }
- Listen to custom events
('localStorageChange', function(event) { if ( === 'groupID') { ('New value:', ); } });
Method 2: Use timer to poll
Another way is to poll within a certain time intervallocalStorage
value, check whether there has been any change.
let lastValue = ('groupID'); setInterval(function() { const newValue = ('groupID'); if (newValue !== lastValue) { ('New value:', newValue); lastValue = newValue; } }, 1000); // Check once every second
Method 3: Use Proxy object
If you want tolocalStorage
The operation is used as a proxy, and can be usedProxy
Object.
const localStorageProxy = new Proxy(localStorage, { set(target, key, value) { (key, value); const event = new CustomEvent('localStorageChange', { detail: { key, value } }); (event); return true; } }); // Use proxy objects when setting values = 'newValue'; // Listen to custom events('localStorageChange', function(event) { if ( === 'groupID') { ('New value:', ); } });
Example: Enable inter-page communication through localStorage listening
Suppose we have two pages, page A is setlocalStorage
IngroupID
Value, page B monitorgroupID
Changes and perform corresponding logic based on the latest value.
Page A: Set localStorage and trigger custom events
const sss = (node, data) => { let id = ('_')[1]; alert(id); ('groupID', id); // Manually trigger custom events const event = new CustomEvent('localStorageChange', { detail: { key: 'groupID', value: id } }); (event); };
Page B: Listen to custom events and get the latest groupID value
mounted() { let _this = this; // Get data during the first load _this.getData(); // Use custom events to listen for groupID changes ('localStorageChange', function(event) { if ( === 'groupID') { alert('1'); _this.getData(); } }); }, methods: { async getData() { const id = ('groupID'); // Check if the id exists if (!id) { this.$message({ message: 'Group ID does not exist, please select a group first. ', type: 'warning' }); return; } try { const res = await ({ page: .page_num, size: , search: .search_field, groupID: id, ... }); if ( === 200) { = ; (, ''); = ; } else { this.$message({ message: , type: 'error' }); } } catch (error) { (error); this.$message({ message: 'The request failed, please try again later. ', type: 'error' }); } } }
The above is the detailed summary of the implementation method of JavaScript listening for localStorage changes in real time. For more information about JavaScript listening for localStorage changes, please pay attention to my other related articles!