-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathchromeApiMock.ts
113 lines (108 loc) · 2.76 KB
/
chromeApiMock.ts
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
105
106
107
108
109
110
111
112
113
// Mock not supported chrome.* API for Firefox and Electron
const isElectron = navigator.userAgent.includes('Electron');
const isFirefox = navigator.userAgent.includes('Firefox');
// Background page only
if (
(isElectron && location.pathname === '/background.bundle.js') ||
isFirefox
) {
(chrome.runtime as any).onConnectExternal = {
addListener() {
// do nothing.
},
};
(chrome.runtime as any).onMessageExternal = {
addListener() {
// do nothing.
},
};
if (isElectron) {
(chrome.notifications as any) = {
onClicked: {
addListener() {
// do nothing.
},
},
create() {
// do nothing.
},
clear() {
// do nothing.
},
};
(chrome.contextMenus as any) = {
onClicked: {
addListener() {
// do nothing.
},
},
};
(chrome.commands as any) = {
onCommand: {
addListener() {
// do nothing.
},
},
};
} else {
(chrome.storage as any).sync = chrome.storage.local;
(chrome.runtime as any).onInstalled = {
addListener: (cb: any) => cb(),
};
}
}
if (isElectron) {
if (!chrome.storage.local || !chrome.storage.local.remove) {
(chrome.storage as any).local = {
set(items: { [key: string]: string }, callback: () => void) {
for (const [key, value] of Object.entries(items)) {
localStorage.setItem(key, value);
}
if (callback) {
callback();
}
},
get(
keys: { [key: string]: any },
callback: (items: { [key: string]: any }) => void,
) {
const result = Object.fromEntries(
Object.entries(keys).map(([key, value]) => [
key,
localStorage.getItem(key) ?? value,
]),
);
if (callback) {
callback(result);
}
},
// Electron ~ 1.4.6
remove(keys: string | string[], callback: () => void) {
if (Array.isArray(keys)) {
for (const key of keys) {
localStorage.removeItem(key);
}
} else {
localStorage.removeItem(keys);
}
if (callback) {
callback();
}
},
};
}
// Avoid error: chrome.runtime.sendMessage is not supported responseCallback
const originSendMessage = (chrome.runtime as any).sendMessage;
(chrome.runtime as any).sendMessage = function (...args: unknown[]) {
if (process.env.NODE_ENV === 'development') {
return originSendMessage(...args);
}
if (typeof args[arguments.length - 1] === 'function') {
Array.prototype.pop.call(args);
}
return originSendMessage(...args);
};
}
if (isFirefox || isElectron) {
(chrome.storage as any).sync = chrome.storage.local;
}