File size: 1,868 Bytes
4d70170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
88
89
90
91
92
import { target } from './env'

// If we can, we use the browser extension API to store data
// it's async though, so we synchronize changes from an intermediate
// storageData object
const useStorage = typeof target.chrome !== 'undefined' && typeof target.chrome.storage !== 'undefined'

let storageData = null

export function initStorage(): Promise<void> {
  return new Promise((resolve) => {
    if (useStorage) {
      target.chrome.storage.local.get(null, (result) => {
        storageData = result
        resolve()
      })
    }
    else {
      storageData = {}
      resolve()
    }
  })
}

export function getStorage(key: string, defaultValue: any = null) {
  checkStorage()
  if (useStorage) {
    return getDefaultValue(storageData[key], defaultValue)
  }
  else {
    try {
      return getDefaultValue(JSON.parse(localStorage.getItem(key)), defaultValue)
    }
    catch (e) {}
  }
}

export function setStorage(key: string, val: any) {
  checkStorage()
  if (useStorage) {
    storageData[key] = val
    target.chrome.storage.local.set({ [key]: val })
  }
  else {
    try {
      localStorage.setItem(key, JSON.stringify(val))
    }
    catch (e) {}
  }
}

export function removeStorage(key: string) {
  checkStorage()
  if (useStorage) {
    delete storageData[key]
    target.chrome.storage.local.remove([key])
  }
  else {
    try {
      localStorage.removeItem(key)
    }
    catch (e) {}
  }
}

export function clearStorage() {
  checkStorage()
  if (useStorage) {
    storageData = {}
    target.chrome.storage.local.clear()
  }
  else {
    try {
      localStorage.clear()
    }
    catch (e) {}
  }
}

function checkStorage() {
  if (!storageData) {
    throw new Error('Storage wasn\'t initialized with \'init()\'')
  }
}

function getDefaultValue(value, defaultValue) {
  if (value == null) {
    return defaultValue
  }
  return value
}