Skip to content

Instantly share code, notes, and snippets.

@tomasperezv
Last active June 12, 2018 21:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomasperezv/5175824 to your computer and use it in GitHub Desktop.
Save tomasperezv/5175824 to your computer and use it in GitHub Desktop.
Communication between multiple tabs, using local storage changes
// User has 2 tabs open: Page 1 and Page 2, both in the same domain
// , subdomain and protocotol
// Page1: https://subdomain.domain.com
...
var data = {
a: 5,
// Local storage won't be triggered unless the value is different,
// so we add a random identifier.
id: Math.floor((Math.random()*1000)+1)
};
localStorage.setItem('connected', JSON.stringify(data))
...
// Page2: https://subdomain.domain.com
...
var onStorage = function(data) {
if (data.key == 'connected') {
try {
var message = JSON.parse(data.newValue);
console.log(message.a); => 5
} catch (e) {
// Invalid JSON
}
}
};
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment