JavaScript Storage Event url Property: Understanding the Storage URL
The JavaScript StorageEvent interface provides crucial information when changes occur in web storage (both localStorage and sessionStorage). Among its properties, the url property is particularly useful. It provides the URL of the document where the storage change occurred. This guide will explain the purpose of the url property, its syntax, and provide practical examples.
What is the url Property?
The url property of a StorageEvent object returns a string representing the URL of the document in which the storage change was initiated. This is particularly helpful when multiple tabs or windows are open, as it allows you to identify the source of the storage event. When a storage event is triggered, it is dispatched to all Window objects that have access to the Storage object (i.e, other tabs or windows), except the one that initiated the change.
Purpose of the url Property
- Identifying the source: Knowing the origin of storage changes can be vital for debugging and understanding the flow of data in multi-tab applications.
- Tracking interactions: Allows developers to trace which part of their application or which specific user action is triggering a storage event.
- Data synchronization: It is crucial for synchronizing application state across different browser windows or tabs, by allowing you to handle changes in a targeted way.
Syntax of the url Property
The url property is read-only and accessed directly from the StorageEvent object.
event.url;
Here, event is an instance of StorageEvent. It does not take any arguments, and it simply returns a string representing the URL.
Important Properties of Storage Event
Before diving deeper into examples, let’s quickly review some important properties of the StorageEvent object:
| Property | Type | Description |
|---|---|---|
| `key` | String | The key of the storage item that was changed. |
| `oldValue` | String or null | The previous value of the storage item. |
| `newValue` | String or null | The new value of the storage item. |
| `storageArea` | Object | The Storage object that was affected (`localStorage` or `sessionStorage`). |
| `url` | String | The URL of the document where the change happened. |
Examples of Using the url Property
Let’s delve into a few practical examples to illustrate how to use the url property effectively.
Example 1: Basic Usage
In this example, we’ll set a value in localStorage and then listen to the storage event on another tab to display the url of the origin.
HTML:
<div id="storageEventDiv">
<p>Storage Event Details will be shown here.</p>
<p id="storageUrlDisplay1"></p>
</div>
JavaScript:
// Set item in localStorage
localStorage.setItem("myKey", "Initial Value");
// Listener for storage event
window.addEventListener("storage", function(event_storage1) {
document.getElementById("storageUrlDisplay1").innerText = `URL: ${event_storage1.url}`;
});
// Set a value again in localStorage. Try it different tab, you will see change url.
setTimeout(() => {localStorage.setItem("myKey", "Updated Value");}, 2000);
Output:
Initially, the paragraph with the id storageUrlDisplay1 will be empty. After a short delay, we trigger a storage event that will change the paragraph content. When you execute this in two tabs, you will see the url changes based on which tab changed the storage data.
Explanation:
- We use
localStorage.setItem()to create/update a value with the key “myKey”. - We add an event listener to the
windowfor thestorageevent. - Inside the event listener,
event_storage1.urlretrieves the URL of the document where the storage change was initiated. - This URL is then displayed in the paragraph with the id “storageUrlDisplay1”.
- The
setTimeout()changes the value of the item after 2 seconds. If you open this in multiple tabs, theurlwill be shown correctly in other tabs.
Note: The storage event does not trigger in the same tab where the change happens. Try to open the HTML in a new tab, you will see the event is triggered correctly. 💡
Example 2: Using url with Multiple Tabs
This example demonstrates how to use the url property to differentiate between changes from different tabs/windows.
HTML
<div id="storageEventDiv2">
<p>Storage Event Details will be shown here.</p>
<p id="storageUrlDisplay2"></p>
</div>
JavaScript:
// Listener for storage event
window.addEventListener("storage", function(event_storage2) {
const urlElement = document.getElementById('storageUrlDisplay2');
if (event_storage2.key === "myKey2"){
urlElement.innerText = `Change Initiated from : ${event_storage2.url}`;
}
});
// Set item in localStorage. Try this in different tabs
setTimeout(() => {localStorage.setItem("myKey2", "Initial Value");}, 2000);
Output:
Initially, the paragraph with the id storageUrlDisplay2 will be empty. After a short delay, we trigger a storage event that will change the paragraph content. If you open this HTML in multiple tabs, the output will show the URL of the document where the change happened, enabling you to distinguish between changes from different tabs.
Explanation:
- We added an event listener to the
windowobject for thestorageevent. - Inside the event listener, we verify
event_storage2.key === "myKey2"to listen for only events with the keymyKey2. - Then, we use
event_storage2.urlto display the source URL of the change. - The
setTimeoutis added to simulate a change. Try this example by opening it in multiple tabs and changing the storage value in one tab to see the result on others.
This setup allows you to track which tab is initiating the storage change, which is crucial for debugging and managing state in applications across multiple tabs.
Example 3: Using url for Debugging
This example shows how to log the source URL for debugging storage events.
HTML:
<div id="storageEventDiv3">
<p>Storage Event Details will be logged to the console.</p>
</div>
JavaScript:
// Event listener for storage event
window.addEventListener('storage', function(event_storage3) {
console.log('Storage change detected from URL:', event_storage3.url);
});
// Change localStorage value
setTimeout(() => {localStorage.setItem('myKey3', 'New Value');}, 2000);
Output:
The output will be visible in the console. If you try this example in multiple tabs, you will see the url logged in other tabs’ console which changed the value.
Explanation:
- We added an event listener for the
storageevent. - Inside the event listener,
console.logdisplays the URL fromevent_storage3.url. This helps in debugging by clearly identifying which tab triggered the change. - We used a
setTimeoutto simulate change. Try this example by opening it in multiple tabs and changing the storage value to see which tab logged the event on console.
This approach can be very helpful when dealing with complex application states across multiple tabs, as it pinpoints the exact source of storage modifications.
Example 4: Using the url for Targeted Actions
Here, we’ll use the url property to perform specific actions based on which tab initiated the storage change.
HTML:
<div id="storageEventDiv4">
<p>Storage Event Details will be shown here.</p>
<p id="storageUrlDisplay4"></p>
</div>
JavaScript:
// Event listener for the storage event
window.addEventListener('storage', function(event_storage4) {
const urlElement = document.getElementById('storageUrlDisplay4');
if (event_storage4.key === 'myKey4') {
if(event_storage4.url.includes('localhost') ){
urlElement.innerText = `Change initiated from localhost: ${event_storage4.url}`;
}
else {
urlElement.innerText = `Change initiated from other domain: ${event_storage4.url}`;
}
}
});
// Simulate change after 2 seconds
setTimeout(() => {
localStorage.setItem('myKey4', 'Yet Another Value');
}, 2000);
Output:
The output paragraph will display if the storage changed from the localhost or not.
Explanation:
- We add an event listener for the
storageevent. - We checked if the key is
myKey4. - Inside, we used
event_storage4.urland check if it includes the textlocalhost. - Based on the condition, it displays a message.
- The
setTimeoutsimulates the change after 2 seconds.
This approach can be used to implement different behaviours based on the source of storage event.
Real-World Use Cases
The url property is crucial in real-world scenarios:
- Multi-tab Applications: For maintaining state consistency across multiple browser tabs or windows of the same application.
- Cross-domain Communication: When different domains or subdomains share and update data via web storage.
- Collaboration Tools: Applications where multiple users might be accessing and modifying the same storage from different locations.
- State Management: For more advanced state management in Single Page Applications (SPAs) by allowing more controlled management of storage changes based on source.
Browser Support
The url property of the StorageEvent object enjoys full support in all modern web browsers:
| Browser | Support |
|——————|———|
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| Edge | Yes |
| Opera | Yes |
| Internet Explorer| No |
Note: While the url property is not available in Internet Explorer, this is not a concern for most modern projects. 🌐
Conclusion
The url property of the StorageEvent object is an essential tool for managing and debugging web storage events. It allows developers to identify the origin of storage changes and enable more precise state management, especially in multi-tab or multi-window environments. By understanding and utilizing this property, you can build more robust, reliable, and user-friendly web applications.








