The data stored in the local storage is available to any document with the same origin.
The storage event is triggered when one document makes a change to the local storage.
We can listen to this event in other documents from the same origin.
The object dispatched with the storage event is a StorageEvent object.
Its members are described in the following table.
Name | Description | Returns |
---|---|---|
key | Gets the key that has been changed | string |
oldValue | Gets the old value associated with the key | string |
newValue | Gets the new value associated with the key | string |
url | Gets the URL of the document that made the change | string |
storageArea | Gets the Storage object which has changed | Storage |
The following code shows a document that listens and categorizes the events issued by the local storage object.
<!DOCTYPE HTML> <html> <body> <table id="data" border="1"> <tr> <th>key</th> <th>oldValue</th> <th>newValue</th> <th>url</th> <th>storageArea</th> </tr> </table> <script> let tableElem = document.getElementById("data"); /*w w w.j a v a2 s. com*/ window.onstorage = handleStorage; function handleStorage(e) { let row = "<tr>"; row += "<td>" + e.key + "</td>"; row += "<td>" + e.oldValue + "</td>"; row += "<td>" + e.newValue + "</td>"; row += "<td>" + e.url + "</td>"; row += "<td>" + (e.storageArea == localStorage) + "</td></tr>"; tableElem.innerHTML += row; }; </script> </body> </html>
The storage event is triggered through the Window object of any document that shares the changed storage.
Events are not dispatched within the document that made the change.
The events are only available in other documents from the same origin.