We all know that the following two conditions must be met to trigger window.onstorage:
The second condition above, simply put, is: either the initialization of storage, because the storage does not exist, its value is null; or it is the update of existing storage.
Example:
// Initialize storagewindow.localStorage.setItem('a', 123); // Register onstorage event window.onstorage = (e) => { console.log(e);}; // Update storagewindow.localStorage.setItem(' a', 123);The last line of code above does not trigger the onstorage event, because the value of a has not changed, it is 123 before and after, so the browser determines that this update is invalid.
Since the onstorage event is triggered by the browser, if we open multiple pages under the same domain name and execute the window.localStorage.setItem method on any one of them (we must also ensure that the second item mentioned at the beginning of the article is met) condition), then if other pages listen to the onstorage event, the onstorage event callbacks in these pages will be executed.
Example:
// http://www.example.com/a.html<script>// Register onstorage event window.onstorage = (e) => { console.log(e);};</script> // http://www.example.com/b.html<script>// Register onstorage event window.onstorage = (e) => { console.log(e);};</script> // http://www.example.com/c.html<script>// Trigger onstorage event window.localStorage.setItem('a', new Date().getTime());</script>As long as page c is ensured to be opened after pages a and b (even if the three pages are not in the same browser window, you need to distinguish the difference between the window and the tab page), then the onstorage events in pages a and b will be triggered.
Now that we know how to use storage events to achieve communication between pages, what use does this communication have for us?
In fact, we only need to know which storage update operation triggered the onstorage event. So how do we know? The onstorage event callback, like other event callback functions, also receives an event object parameter. There are three useful properties in this object. They are:
Combining these 3 key attributes, we can achieve data synchronization between pages
Finally, let me mention the difference between localStorage and sessionStorage
The data stored in localStorage has no expiration time setting, and the data stored in sessionStorage will be cleared when the page session ends.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.