-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (93 loc) · 2.45 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/** @enum {number} */
export const Browser = {
FIREFOX: 0,
CHROME: 1,
SAFARI: 2,
ANDROID: 3
};
export const BROWSER = (() => {
if (/Firefox/.exec(navigator.userAgent)) {
return Browser.FIREFOX;
}
if (window.isAndroid || window.chrome == null) {
return Browser.ANDROID;
}
if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
return Browser.SAFARI;
}
return Browser.CHROME;
})();
function mangleStorageKey(key, version='') {
return `${version || storage.version}$$${key}`;
}
async function getStorage(key, version='') {
const versionKey = mangleStorageKey(key, version);
const result = await this.rawGet(versionKey);
return result ? result[versionKey] : result;
}
async function setStorage(key, value, version='') {
const versionKey = mangleStorageKey(key, version);
let obj = {};
obj[versionKey] = value;
return await this.rawSet(obj);
}
Storage.prototype.get = getStorage;
Storage.prototype.set = setStorage;
module.exports = { Storage };
/**
* @constructor
* @param {String} version
*/
function Storage(version) {
this.version = version;
switch (BROWSER) {
case Browser.ANDROID:
this.rawGet = async key => {
let data = {};
try {
data[key] = JSON.parse(localStorage[key]);
} catch (e) {
data[key] = localStorage[key];
}
return data;
};
this.rawSet = async obj => {
let key = Object.keys(obj)[0];
localStorage[key] = JSON.stringify(obj[key]);
};
break;
case Browser.FIREFOX:
// @ts-ignore
// eslint-disable-next-line no-undef
browser.storage.onChanged.addListener(updateChangedStores);
this.rawGet = async (key) => {
// @ts-ignore
// eslint-disable-next-line no-undef
return await browser.storage.local.get(key);
};
this.rawSet = async (obj) => {
// @ts-ignore
// eslint-disable-next-line no-undef
return await browser.storage.local.set(obj);
};
break;
default:
// @ts-ignore
// eslint-disable-next-line no-undef
chrome.storage.onChanged.addListener(updateChangedStores);
this.rawGet = (key) => {
return new Promise((res) => {
// @ts-ignore
// eslint-disable-next-line no-undef
chrome.storage.local.get(key, res);
});
};
this.rawSet = (obj) => {
return new Promise((res) => {
// @ts-ignore
// eslint-disable-next-line no-undef
chrome.storage.local.set(obj, res);
});
};
}
}