Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an event from a tab/window to another with jQuery/Javascript

How does soundcloud do to stop current playing sound when another soundcloud window or tab is playing ?

I'm looking for a way to send an event from a tab/window to another one, without using Child Window design.

I tried to use custom Cookie event but it did not affect other tabs.

like image 453
David Avatar asked Jan 01 '26 21:01

David


1 Answers

Use localStorage.

Did you know that localStorage fires an event? More specifically, it fires an event whenever an item is added, modified, or removed in another browsing context. Effectively, this means that whenever you touch localStorage in any given tab, all other tabs can learn about it by listening for the storage event on the window object, like so:

window.addEventListener('storage', function(e){
  console.log(event.key, event.newValue);
});

Whenever a tab modifies something in localStorage, an event fires in every other tab. This means we're able to communicate across browser tabs simply by setting values on localStorage.

See the local-storage module by the author of that article that offers an API that might be of some use to you:

ls.on(key, fn(value, old, url))
ls.off(key, fn)
like image 130
idbehold Avatar answered Jan 03 '26 10:01

idbehold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!