UNPKG

1.39 kBJavaScriptView Raw
1/* global localStorage, addEventListener */
2
3/**
4 * Isomorphic variable storage.
5 *
6 * Uses LocalStorage in the browser and falls back to in-memory storage.
7 *
8 * @module storage
9 */
10
11/* istanbul ignore next */
12class VarStoragePolyfill {
13 constructor () {
14 this.map = new Map()
15 }
16
17 /**
18 * @param {string} key
19 * @param {any} newValue
20 */
21 setItem (key, newValue) {
22 this.map.set(key, newValue)
23 }
24
25 /**
26 * @param {string} key
27 */
28 getItem (key) {
29 return this.map.get(key)
30 }
31}
32
33/* istanbul ignore next */
34/**
35 * @type {any}
36 */
37let _localStorage = new VarStoragePolyfill()
38let usePolyfill = true
39
40try {
41 // if the same-origin rule is violated, accessing localStorage might thrown an error
42 /* istanbul ignore next */
43 if (typeof localStorage !== 'undefined') {
44 _localStorage = localStorage
45 usePolyfill = false
46 }
47} catch (e) { }
48
49/* istanbul ignore next */
50/**
51 * This is basically localStorage in browser, or a polyfill in nodejs
52 */
53export const varStorage = _localStorage
54
55/* istanbul ignore next */
56/**
57 * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.
58 *
59 * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler
60 * @function
61 */
62export const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))