Last active
June 12, 2018 21:15
-
-
Save tomasperezv/5175824 to your computer and use it in GitHub Desktop.
Communication between multiple tabs, using local storage changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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