Skip to content

Instantly share code, notes, and snippets.

@maremarismaria
Created August 31, 2023 06:10
Show Gist options
  • Save maremarismaria/032ee9251eeda513d0c81843891bc182 to your computer and use it in GitHub Desktop.
Save maremarismaria/032ee9251eeda513d0c81843891bc182 to your computer and use it in GitHub Desktop.
Triggering Custom Events with Web Storage API & TypeScript
enum StorageKey {
SESSION_STORAGE_KEY = "auth",
TEMP_SESSION_STORAGE_KEY = "temp_auth",
GET_SESSION = "get_session",
CLEAR_SESSION = "clear_session",
}
const triggerAction = (key: StorageKey) => {
localStorage.setItem(key, "indifferent");
localStorage.removeItem(key);
}
/**
* Trigger for cleaning the session
*/
export const clearSession = () => {
if (sessionStorage.length) {
triggerAction(StorageKey.CLEAR_SESSION);
}
}
/**
* Trigger for start asking session data to other tabs
*/
const getSession = () => {
if (!sessionStorage.length) {
triggerAction(StorageKey.GET_SESSION);
}
}
/**
* Copy current session data from sessionStorage into the temp storage in localStorage
* @param storageKey Session storage key where the session is stored
*/
const copySession = (storageKey: string) => {
const sessionData = sessionStorage.getItem(storageKey);
if (sessionData) {
localStorage.setItem(StorageKey.TEMP_SESSION_STORAGE_KEY, JSON.stringify(sessionData));
localStorage.removeItem(StorageKey.TEMP_SESSION_STORAGE_KEY);
}
}
/**
* Set data into the session storage object
* @param storageKey Session storage key where the session will be stored
* @param data Value for saving into the session storage object
*/
const setSession = (storageKey: string, data: string) => {
const sessionData = JSON.parse(data);
if (sessionData) {
sessionStorage.setItem(storageKey, sessionData);
}
}
const removeSession = () => {
sessionStorage.clear();
}
const storageHandler = (storageKey: string) => (event: StorageEvent) => {
if (!event.newValue) {
return;
}
// Tab is requesting session
if (StorageKey.GET_SESSION === event.key) {
copySession(storageKey);
// Tab is sending the temporal data and there is no session yet
} else if (StorageKey.TEMP_SESSION_STORAGE_KEY === event.key && !sessionStorage.length) {
setSession(storageKey, event.newValue);
// Tab is cleaning some session
} else if (StorageKey.CLEAR_SESSION === event.key) {
removeSession();
}
}
export const storageListener = (storageKey = StorageKey.SESSION_STORAGE_KEY) => {
window.addEventListener("storage", storageHandler(storageKey));
getSession();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment