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