-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathbrowser-compat.ts
More file actions
54 lines (50 loc) · 1.73 KB
/
browser-compat.ts
File metadata and controls
54 lines (50 loc) · 1.73 KB
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
const SESSION_PREFIX = '__sp_session__:'
let sessionSupported: boolean | null = null
const checkSessionSupport = async (): Promise<boolean> => {
if (sessionSupported !== null) return sessionSupported
try {
await chrome.storage.session.get('__probe__')
sessionSupported = true
} catch {
sessionSupported = false
}
return sessionSupported
}
export const compatStorage = {
session: {
get: async (key: string): Promise<Record<string, unknown>> => {
if (await checkSessionSupport()) {
return chrome.storage.session.get(key)
}
const storageKey = SESSION_PREFIX + key
const result = await chrome.storage.local.get(storageKey)
return Object.prototype.hasOwnProperty.call(result, storageKey)
? { [key]: result[storageKey] }
: {}
},
set: async (items: Record<string, unknown>): Promise<void> => {
if (await checkSessionSupport()) {
return chrome.storage.session.set(items)
}
const prefixed: Record<string, unknown> = {}
for (const [key, value] of Object.entries(items)) {
prefixed[SESSION_PREFIX + key] = value
}
return chrome.storage.local.set(prefixed)
},
remove: async (keys: string[]): Promise<void> => {
if (await checkSessionSupport()) {
return chrome.storage.session.remove(keys)
}
return chrome.storage.local.remove(keys.map(k => SESSION_PREFIX + k))
}
}
}
export const clearLegacySessionKeys = async (): Promise<void> => {
if (await checkSessionSupport()) return
const all = await chrome.storage.local.get(null)
const sessionKeys = Object.keys(all).filter(k => k.startsWith(SESSION_PREFIX))
if (sessionKeys.length) {
await chrome.storage.local.remove(sessionKeys)
}
}