Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Last active November 12, 2018 11:24
Show Gist options
  • Save laphilosophia/d5c8e57819b624791fe2caf0b4e67705 to your computer and use it in GitHub Desktop.
Save laphilosophia/d5c8e57819b624791fe2caf0b4e67705 to your computer and use it in GitHub Desktop.
storage api listener
// Listener
window.addEventListener('storage', handlerEvent)
// Whenever we set a localStorage, window object will listen and invoke this handlerEvent function.
// We do all validation and stuff to act accordingly.
// Handler
const handlerEvent = event => {
if (event.originalEvent.key != 'message') return
let message = JSON.parse(event.originalEvent.newValue)
if (!message) return
if (message.command == 'logout') {
// logout ()
} else if (message.command == 'login') {
// login()
} else {
// default()
}
}
// Console log the event object to know more
// Speaker
const invokeMessage = message => {
localStorage.setItem('message', JSON.stringify(message))
localStorage.removeItem('message')
}
// Thats It. All set
// Give key to Speaker
invokeMessage({ 'command' : 'login' })
// When speaker speaks listener has to listen no choice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment