UNPKG

kawkab-frontend

Version:

Kawkab frontend is a frontend library for the Kawkab framework

100 lines (99 loc) 2.35 kB
/** * Checks if sessionStorage is available and usable. * @returns {boolean} True if supported, false otherwise. */ function isSupported() { try { if (typeof window === 'undefined' || !window.sessionStorage) { return false; } const testKey = '__test__'; window.sessionStorage.setItem(testKey, testKey); window.sessionStorage.removeItem(testKey); return true; } catch (e) { return false; } } /** * Retrieves a value from sessionStorage and parses it as JSON. * @param key The key to retrieve. * @returns The stored value, or null if not found or on error. */ function get(key, defaultValue) { if (!isSupported()) { return null; } try { const value = window.sessionStorage.getItem(key); if (value === null) { return defaultValue || null; } try { return JSON.parse(value); } catch { return value; } } catch (error) { console.error(`Error getting from sessionStorage: ${key}`, error); return null; } } /** * Stores a value in sessionStorage after serializing it to JSON. * @param key The key to store the value under. * @param value The value to store (can be any JSON-serializable type). */ function set(key, value) { if (!isSupported()) { return; } try { const stringValue = JSON.stringify(value); window.sessionStorage.setItem(key, stringValue); } catch (error) { console.error(`Error setting to sessionStorage: ${key}`, error); } } /** * Checks if a key exists in sessionStorage. * @param key The key to check. * @returns True if the key exists, false otherwise. */ function has(key) { if (!isSupported()) { return false; } return window.sessionStorage.getItem(key) !== null; } /** * Removes an item from sessionStorage. * @param key The key to remove. */ function remove(key) { if (!isSupported()) { return; } window.sessionStorage.removeItem(key); } /** * Clears all items from sessionStorage. */ function clear() { if (!isSupported()) { return; } window.sessionStorage.clear(); } export const SessionStorage = { get, set, has, remove, clear, isSupported, };