-
Notifications
You must be signed in to change notification settings - Fork 1k
/
chromeAPIMock.js
92 lines (86 loc) · 2.2 KB
/
chromeAPIMock.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
// Mock not supported chrome.* API for Firefox and Electron
window.isElectron = window.navigator &&
window.navigator.userAgent.indexOf('Electron') !== -1;
const isFirefox = navigator.userAgent.indexOf('Firefox') !== -1;
// Background page only
if (
window.isElectron &&
location.pathname === '/_generated_background_page.html' ||
isFirefox
) {
chrome.runtime.onConnectExternal = {
addListener() {}
};
chrome.runtime.onMessageExternal = {
addListener() {}
};
if (window.isElectron) {
chrome.notifications = {
onClicked: {
addListener() {}
},
create() {},
clear() {}
};
chrome.contextMenus = {
onClicked: {
addListener() {}
}
};
} else {
chrome.storage.sync = chrome.storage.local;
chrome.runtime.onInstalled = {
addListener: cb => cb()
};
}
}
if (window.isElectron) {
if (!chrome.storage.local || !chrome.storage.local.remove) {
chrome.storage.local = {
set(obj, callback) {
Object.keys(obj).forEach(key => {
localStorage.setItem(key, obj[key]);
});
if (callback) {
callback();
}
},
get(obj, callback) {
const result = {};
Object.keys(obj).forEach(key => {
result[key] = localStorage.getItem(key) || obj[key];
});
if (callback) {
callback(result);
}
},
// Electron ~ 1.4.6
remove(items, callback) {
if (Array.isArray(items)) {
items.forEach(name => {
localStorage.removeItem(name);
});
} else {
localStorage.removeItem(items);
}
if (callback) {
callback();
}
}
};
}
// Avoid error: chrome.runtime.sendMessage is not supported responseCallback
const originSendMessage = chrome.runtime.sendMessage;
chrome.runtime.sendMessage = function() {
if (process.env.NODE_ENV === 'development') {
return originSendMessage(...arguments);
}
if (typeof arguments[arguments.length - 1] === 'function') {
Array.prototype.pop.call(arguments);
}
return originSendMessage(...arguments);
};
}
if (isFirefox) {
chrome.storage.sync = chrome.storage.local;
}