Created
April 25, 2019 08:04
-
-
Save werthdavid/d1a781009e70fed2f49246e7a9ebecdc to your computer and use it in GitHub Desktop.
Special Storage-Implementation that uses sessionStorage (like the default of the OAuth-library) but also sets a marker in localStorage so that other Browser-Tabs get notified when the user on this Tab logs out.
This file contains 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
/** | |
* Special Storage-Implementation that uses sessionStorage (like the default of the | |
* OAuth-library) but also sets a marker in localStorage so that other Browser-Tabs | |
* get notified when the user on this Tab logs out. | |
*/ | |
export class CrossTabStorage extends OAuthStorage { | |
readonly MARKER_KEY = "LOGGED_IN"; | |
constructor() { | |
super(); | |
// We listen to changes on localstorage (the listener will only be fired if | |
// another Browser-Tab makes changes) | |
window.addEventListener("storage", (event: StorageEvent) => { | |
if (event.key === this.MARKER_KEY) { | |
// Another Browser-Tab removed the magic entry in localStorage (he logged out) | |
// so we remove our tokens as well | |
sessionStorage.clear(); | |
} | |
}); | |
} | |
getItem(key: string): string { | |
return sessionStorage.getItem(key); | |
} | |
removeItem(key: string): void { | |
sessionStorage.removeItem(key); | |
if (key === "access_token") { | |
// User has logged out on this Browser-Tab | |
// Remove the magic entry on localStorage to tell other Browser-Tabs that they should | |
// clear their session storage | |
localStorage.removeItem(this.MARKER_KEY); | |
} | |
} | |
setItem(key: string, data: string): void { | |
sessionStorage.setItem(key, data); | |
if (key === "access_token") { | |
// User has logged in on this Browser-Tab | |
// Set the magic entry that, when removed, fires events on other Browser-Tabs | |
localStorage.setItem(this.MARKER_KEY, "true"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment