This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
webext-domain-permission-toggle.js
221 lines (213 loc) · 8.11 KB
/
webext-domain-permission-toggle.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/* https://github.com/fregante/webext-domain-permission-toggle @ v2.1.0 */
var addDomainPermissionToggle = (function () {
'use strict';
function NestedProxy(target) {
return new Proxy(target, {
get(target, prop) {
if (typeof target[prop] !== 'function') {
return new NestedProxy(target[prop]);
}
return (...arguments_) =>
new Promise((resolve, reject) => {
target[prop](...arguments_, result => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
} else {
resolve(result);
}
});
});
}
});
}
const chromeP =
typeof window === 'object' &&
(window.browser || new NestedProxy(window.chrome));
const patternValidationRegex = /^(https?|wss?|file|ftp|\*):\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^file:\/\/\/.*$|^resource:\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^about:/;
const isFirefox = typeof navigator === 'object' && navigator.userAgent.includes('Firefox/');
function getRawRegex(matchPattern) {
if (!patternValidationRegex.test(matchPattern)) {
throw new Error(matchPattern + ' is an invalid pattern, it must match ' + String(patternValidationRegex));
}
let [, protocol, host, pathname] = matchPattern.split(/(^[^:]+:[/][/])([^/]+)?/);
protocol = protocol
.replace('*', isFirefox ? '(https?|wss?)' : 'https?')
.replace(/[/]/g, '[/]');
host = (host !== null && host !== void 0 ? host : '')
.replace(/^[*][.]/, '([^/]+.)*')
.replace(/^[*]$/, '[^/]+')
.replace(/[.]/g, '[.]')
.replace(/[*]$/g, '[^.]+');
pathname = pathname
.replace(/[/]/g, '[/]')
.replace(/[.]/g, '[.]')
.replace(/[*]/g, '.*');
return '^' + protocol + host + '(' + pathname + ')?$';
}
function patternToRegex(...matchPatterns) {
if (matchPatterns.includes('<all_urls>')) {
return /^(https?|file|ftp):[/]+/;
}
return new RegExp(matchPatterns.map(getRawRegex).join('|'));
}
const isExtensionContext = typeof chrome === 'object' && chrome && typeof chrome.extension === 'object';
const globalWindow = typeof window === 'object' ? window : undefined;
const isWeb = typeof location === 'object' && location.protocol.startsWith('http');
function isBackgroundPage() {
var _a, _b;
return isExtensionContext && (location.pathname === '/_generated_background_page.html' ||
((_b = (_a = chrome.extension) === null || _a === void 0 ? void 0 : _a.getBackgroundPage) === null || _b === void 0 ? void 0 : _b.call(_a)) === globalWindow);
}
function getManifestPermissionsSync() {
return _getManifestPermissionsSync(chrome.runtime.getManifest());
}
function _getManifestPermissionsSync(manifest) {
var _a, _b;
const manifestPermissions = {
origins: [],
permissions: []
};
const list = new Set([
...((_a = manifest.permissions) !== null && _a !== void 0 ? _a : []),
...((_b = manifest.content_scripts) !== null && _b !== void 0 ? _b : []).flatMap(config => { var _a; return (_a = config.matches) !== null && _a !== void 0 ? _a : []; })
]);
for (const permission of list) {
if (permission.includes('://')) {
manifestPermissions.origins.push(permission);
}
else {
manifestPermissions.permissions.push(permission);
}
}
return manifestPermissions;
}
const isFirefox$1 = typeof navigator === 'object' && navigator.userAgent.includes('Firefox/');
const contextMenuId = 'webext-domain-permission-toggle:add-permission';
let globalOptions;
async function executeCode(tabId, function_, ...args) {
return chromeP.tabs.executeScript(tabId, {
code: `(${function_.toString()})(...${JSON.stringify(args)})`
});
}
async function isOriginPermanentlyAllowed(origin) {
return chromeP.permissions.contains({
origins: [origin + '/*']
});
}
async function getTabUrl(tabId) {
if (isFirefox$1) {
const [url] = await executeCode(tabId, () => location.href);
return url;
}
const tab = await chromeP.tabs.get(tabId);
return tab.url;
}
async function updateItem(url) {
const settings = {
checked: false,
enabled: true
};
if (url) {
const origin = new URL(url).origin;
const manifestPermissions = getManifestPermissionsSync();
const isDefault = patternToRegex(...manifestPermissions.origins).test(origin);
settings.enabled = !isDefault;
settings.checked = isDefault || await isOriginPermanentlyAllowed(origin);
}
chrome.contextMenus.update(contextMenuId, settings);
}
async function togglePermission(tab, toggle) {
const safariError = 'The browser didn\'t supply any information about the active tab.';
if (!tab.url && toggle) {
throw new Error(`Please try again. ${safariError}`);
}
if (!tab.url && !toggle) {
throw new Error(`Couldn't disable the extension on the current tab. ${safariError}`);
}
const permissionData = {
origins: [
new URL(tab.url).origin + '/*'
]
};
if (!toggle) {
void chromeP.permissions.remove(permissionData);
return;
}
const userAccepted = await chromeP.permissions.request(permissionData);
if (!userAccepted) {
chrome.contextMenus.update(contextMenuId, {
checked: false
});
return;
}
if (globalOptions.reloadOnSuccess) {
void executeCode(tab.id, (message) => {
if (confirm(message)) {
location.reload();
}
}, globalOptions.reloadOnSuccess);
}
}
async function handleTabActivated({ tabId }) {
void updateItem(await getTabUrl(tabId).catch(() => ''));
}
async function handleClick({ checked, menuItemId }, tab) {
if (menuItemId !== contextMenuId) {
return;
}
try {
await togglePermission(tab, checked);
}
catch (error) {
if (tab === null || tab === void 0 ? void 0 : tab.id) {
try {
await executeCode(tab.id, 'alert' ,
String(error instanceof Error ? error : new Error(error.message)));
}
catch (_a) {
alert(error);
}
void updateItem();
}
throw error;
}
}
function addDomainPermissionToggle(options) {
if (!isBackgroundPage()) {
throw new Error('webext-domain-permission-toggle can only be called from a background page');
}
if (globalOptions) {
throw new Error('webext-domain-permission-toggle can only be initialized once');
}
const { name, optional_permissions } = chrome.runtime.getManifest();
globalOptions = {
title: `Enable ${name} on this domain`,
reloadOnSuccess: `Do you want to reload this page to apply ${name}?`,
...options
};
if (!chrome.contextMenus) {
throw new Error('webext-domain-permission-toggle requires the `contextMenu` permission');
}
const optionalHosts = optional_permissions === null || optional_permissions === void 0 ? void 0 : optional_permissions.filter(permission => /<all_urls>|\*/.test(permission));
if (!optionalHosts || optionalHosts.length === 0) {
throw new TypeError('webext-domain-permission-toggle some wildcard hosts to be specified in `optional_permissions`');
}
chrome.contextMenus.remove(contextMenuId, () => chrome.runtime.lastError);
chrome.contextMenus.create({
id: contextMenuId,
type: 'checkbox',
checked: false,
title: globalOptions.title,
contexts: ['page_action', 'browser_action'],
documentUrlPatterns: optionalHosts
});
chrome.contextMenus.onClicked.addListener(handleClick);
chrome.tabs.onActivated.addListener(handleTabActivated);
chrome.tabs.onUpdated.addListener(async (tabId, { status }, { url, active }) => {
if (active && status === 'complete') {
void updateItem(url !== null && url !== void 0 ? url : await getTabUrl(tabId).catch(() => ''));
}
});
}
return addDomainPermissionToggle;
}());