This repository has been archived by the owner on Jul 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
76 lines (66 loc) · 2.22 KB
/
index.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
type PermissionChangeCallback = (callback: chrome.permissions.Permissions) => void;
const events = [
['request', 'onAdded'],
['remove', 'onRemoved']
] as const;
if (chrome.permissions && !chrome.permissions.onAdded) {
for (const [action, event] of events) {
const act = chrome.permissions[action];
const listeners = new Set<PermissionChangeCallback>();
// Collect
chrome.permissions[event] = {
addListener(callback) {
listeners.add(callback);
}
};
// Listen into requests and fire callbacks
chrome.permissions[action] = (permissions, callback) => {
const initial = browser.permissions.contains(permissions);
const expected = action === 'request';
act(permissions, async successful => {
if (callback) {
callback(successful);
}
if (!successful) {
return;
}
// Only fire events if they changed
if (await initial !== expected) {
const fullPermissions = {origins: [], permissions: [], ...permissions};
// Firefox won't run asynchronous functions without this
chrome.permissions.getAll(() => {
for (const listener of listeners) {
setTimeout(listener, 0, fullPermissions); // Run all listeners even if one errors
}
});
// Enable polyfill to work across contexts
chrome.runtime.sendMessage({
permissionsEventsPolyfill: permissions
});
}
});
};
// @ts-ignore `onAdded` is specified as `const`, but isn't
browser.permissions[event] = chrome.permissions[event];
// TODO: drop `as 'request'` after https://github.com/jsmnbom/definitelytyped-firefox-webext-browser/issues/22
browser.permissions[action as 'request'] = async (permissions: chrome.permissions.Permissions) => new Promise<boolean>((resolve, reject) => {
chrome.permissions[action](permissions, result => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result);
}
});
});
// Enable polyfill to work across contexts
if (chrome.runtime.onMessage) {
chrome.runtime.onMessage.addListener(message => {
if (message && message.permissionsEventsPolyfill) {
for (const listener of listeners) {
setTimeout(listener, 0, message.permissionsEventsPolyfill);
}
}
});
}
}
}