-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchrome-extension-async.js
160 lines (144 loc) · 7.15 KB
/
chrome-extension-async.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/** Wrap an API that uses callbacks with Promises
* This expects the pattern function withCallback(arg1, arg2, ... argN, callback)
* @author Keith Henry <[email protected]>
* @license MIT */
(function () {
'use strict';
/** Wrap a function with a callback with a Promise.
* @param {function} f The function to wrap, should be pattern: withCallback(arg1, arg2, ... argN, callback).
* @param {function} parseCB Optional function to parse multiple callback parameters into a single object.
* @returns {Promise} Promise that resolves when the callback fires. */
function promisify(f, parseCB) {
return (...args) => {
let safeArgs = args;
let callback;
// The Chrome API functions all use arguments, so we can't use f.length to check
// If there is a last arg
if (args && args.length > 0) {
// ... and the last arg is a function
const last = args[args.length - 1];
if (typeof last === 'function') {
// Trim the last callback arg if it's been passed
safeArgs = args.slice(0, args.length - 1);
callback = last;
}
}
// Return a promise
return new Promise((resolve, reject) => {
try {
// Try to run the original function, with the trimmed args list
f(...safeArgs, (...cbArgs) => {
// If a callback was passed at the end of the original arguments
if (callback) {
// Don't allow a bug in the callback to stop the promise resolving
try { callback(...cbArgs); }
catch (cbErr) { reject(cbErr); }
}
// Chrome extensions always fire the callback, but populate chrome.runtime.lastError with exception details
if (chrome.runtime.lastError)
// Return as an error for the awaited catch block
reject(new Error(chrome.runtime.lastError.message || `Error thrown by API ${chrome.runtime.lastError}`));
else {
if (parseCB) {
const cbObj = parseCB(...cbArgs);
resolve(cbObj);
}
else if (!cbArgs || cbArgs.length === 0)
resolve();
else if (cbArgs.length === 1)
resolve(cbArgs[0]);
else
resolve(cbArgs);
}
});
}
catch (err) { reject(err); }
});
}
}
/** Promisify all the known functions in the map
* @param {object} api The Chrome native API to extend
* @param {Array} apiMap Collection of sub-API and functions to promisify */
function applyMap(api, apiMap) {
if (!api)
// Not supported by current permissions
return;
for (let funcDef of apiMap) {
let funcName;
if (typeof funcDef === 'string')
funcName = funcDef;
else {
funcName = funcDef.n;
}
if (!api.hasOwnProperty(funcName))
// Member not in API
continue;
const m = api[funcName];
if (typeof m === 'function')
// This is a function, wrap in a promise
api[funcName] = promisify(m.bind(api), funcDef.cb);
else
// Sub-API, recurse this func with the mapped props
applyMap(m, funcDef.props);
}
}
/** Apply promise-maps to the Chrome native API.
* @param {object} apiMaps The API to apply. */
function applyMaps(apiMaps) {
for (let apiName in apiMaps) {
const callbackApi = chrome[apiName];
if (!callbackApi)
// Not supported by current permissions
continue;
const apiMap = apiMaps[apiName];
applyMap(callbackApi, apiMap);
}
}
// accessibilityFeatures https://developer.chrome.com/extensions/accessibilityFeatures
const knownA11ySetting = ['get', 'set', 'clear'];
// ContentSetting https://developer.chrome.com/extensions/contentSettings#type-ContentSetting
const knownInContentSetting = ['clear', 'get', 'set', 'getResourceIdentifiers'];
// StorageArea https://developer.chrome.com/extensions/storage#type-StorageArea
const knownInStorageArea = ['get', 'getBytesInUse', 'set', 'remove', 'clear'];
/** Map of API functions that follow the callback pattern that we can 'promisify' */
applyMaps({
bookmarks: [
'get', 'getChildren', 'getRecent', 'getTree', 'getSubTree',
'search', 'create', 'move', 'update', 'remove', 'removeTree'],
browser: ['openTab'],
browserAction: [
'getTitle', 'setIcon', 'getPopup', 'getBadgeText', 'getBadgeBackgroundColor'],
contextMenus: ['create', 'update', 'remove', 'removeAll'],
notifications: ['create', 'update', 'clear', 'getAll', 'getPermissionLevel'],
pageAction: ['getTitle', 'setIcon', 'getPopup'],
pageCapture: ['saveAsMHTML'],
permissions: ['getAll', 'contains', 'request', 'remove'],
platformKeys: ['selectClientCertificates', 'verifyTLSServerCertificate',
{ n: "getKeyPair", cb: (publicKey, privateKey) => { return { publicKey, privateKey }; } }],
runtime: [
'getBackgroundPage', 'openOptionsPage', 'setUninstallURL',
'restartAfterDelay', 'sendMessage',
'sendNativeMessage', 'getPlatformInfo', 'getPackageDirectoryEntry',
{ n: "requestUpdateCheck", cb: (status, details) => { return { status, details }; } }],
scriptBadge: ['getPopup'],
sessions: ['getRecentlyClosed', 'getDevices', 'restore'],
storage: [ // Todo: this should extend StorageArea.prototype instead
{ n: 'sync', props: knownInStorageArea },
{ n: 'local', props: knownInStorageArea },
{ n: 'managed', props: knownInStorageArea }],
tabCapture: ['capture', 'getCapturedTabs'],
tabs: [
'get', 'getCurrent', 'sendMessage', 'create', 'duplicate',
'query', 'highlight', 'update', 'move', 'reload', 'remove',
'detectLanguage', 'captureVisibleTab', 'executeScript',
'insertCSS', 'setZoom', 'getZoom', 'setZoomSettings',
'getZoomSettings', 'discard'],
topSites: ['get'],
tts: ['isSpeaking', 'getVoices', 'speak'],
types: ['set', 'get', 'clear'],
vpnProvider: ['createConfig', 'destroyConfig', 'setParameters', 'sendPacket', 'notifyConnectionStateChanged'],
wallpaper: ['setWallpaper'],
webNavigation: ['getFrame', 'getAllFrames', 'handlerBehaviorChanged'],
windows: ['get', 'getCurrent', 'getLastFocused', 'getAll', 'create', 'update', 'remove']
});
})();