× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Can I make something happen in multiple tabs, or respond to localStorage changes in other tabs?

Rory O'Keeffe
Nov 17, 2016
<p>You can!</p> <p>While you can use sockets.io or Pusher or some other solution for this, the simplest way is just to act on a change to <code>localStorage</code>.</p> <p>We can put an event listener on window which will fire if something changes in <code>localStorage</code> (within the same domain), and let us access the changed key/value pair in the passed Event object.</p> <p>This event will fire in all the open tabs/windows <em>except </em>the tab or window where the change was made, making it easy to react to the event exactly where you need to, without having to check if you're in the tab the user triggered the storage change from.</p> <p><em>Note that this will not work for <code>sessionStorage</code>, as <code>sessionStorage</code> is restricted to just the current tab/window.</em></p> <pre><code class="language-javascript">window.addEventListener('storage', function(evt) { if(evt.key === "keyIReactTo") { doSomething(); } });</code></pre> <p>This can be used for simple things like kicking off a timer in two tabs (that syncs), or updating more complex information. The browser is your oyster!</p> <p>For more information about <code>localStorage</code>, and this event in particular, have a look <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent">here</a>.</p>
comments powered by Disqus