-
Notifications
You must be signed in to change notification settings - Fork 961
/
DOMStateStorage.js
87 lines (72 loc) · 2 KB
/
DOMStateStorage.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import warning from 'warning'
const QuotaExceededErrors = {
QuotaExceededError: true,
QUOTA_EXCEEDED_ERR: true
}
const SecurityErrors = {
SecurityError: true
}
const KeyPrefix = '@@History/'
const createKey = (key) =>
KeyPrefix + key
export const saveState = (key, state) => {
try {
if (!window.sessionStorage) {
// Session storage is not available or hidden.
// sessionStorage is undefined in Internet Explorer when served via file protocol.
warning(
false,
'[history] Unable to save state; sessionStorage is not available'
)
return
}
if (state == null) {
window.sessionStorage.removeItem(createKey(key))
} else {
window.sessionStorage.setItem(createKey(key), JSON.stringify(state))
}
} catch (error) {
if (SecurityErrors[error.name]) {
// Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any
// attempt to access window.sessionStorage.
warning(
false,
'[history] Unable to save state; sessionStorage is not available due to security settings'
)
return
}
if (QuotaExceededErrors[error.name] && window.sessionStorage.length === 0) {
// Safari "private mode" throws QuotaExceededError.
warning(
false,
'[history] Unable to save state; sessionStorage is not available in Safari private mode'
)
return
}
throw error
}
}
export const readState = (key) => {
let json
try {
json = window.sessionStorage.getItem(createKey(key))
} catch (error) {
if (SecurityErrors[error.name]) {
// Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any
// attempt to access window.sessionStorage.
warning(
false,
'[history] Unable to read state; sessionStorage is not available due to security settings'
)
return undefined
}
}
if (json) {
try {
return JSON.parse(json)
} catch (error) {
// Ignore invalid JSON.
}
}
return undefined
}