-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathapi.js
614 lines (509 loc) · 20.1 KB
/
api.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
browser.userScripts.onBeforeScript.addListener(script => {
// --- globals
const {grantRemove, registerMenuCommand, remoteCSS, resourceData, FMUrl, info} = script.metadata;
const {name, id = `_${name}`, injectInto, resources} = info.script; // set id as _name
let {storage} = script.metadata; // storage at the time of registration
const valueChange = {};
const scriptCommand = {};
// const FMUrl = browser.runtime.getURL(''); // used for sourceURL & import
// --- add isIncognito to GM info
if (browser.extension.inIncognitoContext) {
info.isIncognito = true;
info.script.isIncognito = true;
}
class API {
static {
// Script Command registerMenuCommand
registerMenuCommand && browser.runtime.onMessage.addListener(message => {
switch (true) {
case Object.hasOwn(message, 'listCommand'): // to popup.js
const command = Object.keys(scriptCommand);
command[0] && browser.runtime.sendMessage({name, command});
break;
case message.name === name && Object.hasOwn(message, 'command'): // from popup.js
(scriptCommand[message.command])();
break;
}
});
}
// --- Script Storage: direct operation
static async getData() {
return (await browser.storage.local.get(id))[id];
}
static async setStorage() {
const data = await API.getData();
storage = data.storage;
}
static onChanged(changes) {
if (!changes[id]) { return; } // not this userscript
const oldValue = changes[id].oldValue.storage;
const newValue = changes[id].newValue.storage;
// process addValueChangeListener (only for remote) (key, oldValue, newValue, remote)
Object.keys(valueChange).forEach(item =>
!API.equal(oldValue[item], newValue[item]) &&
(valueChange[item])(item, oldValue[item], newValue[item], !API.equal(newValue[item], storage[item]))
);
}
static equal(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
// based on browser.storage.local.get()
// A key (string) or keys (an array of strings, or an object specifying default values)
// to identify the item(s) to be retrieved from storage. If you pass an empty object or array here,
// an empty object will be retrieved. If you pass null, or an undefined value,
// the entire storage contents will be retrieved.
static getStorageValue(thisStorage, key, defaultValue) {
let obj = {};
switch (true) {
case !key:
obj = thisStorage;
break;
case typeof key === 'string':
obj = Object.hasOwn(thisStorage, key) ? thisStorage[key] : defaultValue;
break;
case Array.isArray(key):
key.forEach(i => obj[i] = thisStorage[i]);
break;
default:
Object.entries(key).forEach(([item, def]) =>
obj[item] = Object.hasOwn(thisStorage, item) ? thisStorage[item] : def);
}
return API.prepare(obj); // object or string
}
// --- synch APIs
static GM_getValue(key, defaultValue) {
return API.getStorageValue(storage, key, defaultValue);
}
static GM_listValues() {
return script.export(Object.keys(storage));
}
static GM_getResourceText(resourceName) {
return resourceData[resourceName] || '';
}
// --- sync return GM_getResourceURL
static getResourceUrl(resourceName) {
return resources[resourceName];
}
// --- prepare return value, check if it is primitive value
static prepare(value) {
return ['object', 'function'].includes(typeof value) && value !== null ? script.export(value) : value;
}
// --- auxiliary regex include/exclude test function
static matchURL() {
const {includes, excludes} = info.script;
return (!includes[0] || API.arrayTest(includes)) && (!excludes[0] || !API.arrayTest(excludes));
}
static arrayTest(arr, url = location.href) {
return arr.some(i => new RegExp(i.slice(1, -1), 'i').test(url));
}
// --- cloneInto wrapper for object methods
static cloneIntoBridge(obj, target, options = {}) {
return cloneInto(options.cloneFunctions ? obj.wrappedJSObject : obj, target, options);
}
// --- inject into page context
static injectIntoPage(str) {
str = `((unsafeWindow, GM, GM_info = GM.info) => {(() => { ${str}
})();})(window, ${JSON.stringify({info})});`;
GM.addScript(str);
}
// --- log from background
static log(message, type = 'error') {
browser.runtime.sendMessage({
api: 'log',
name,
data: {message, type}
});
}
static checkURL(url) {
try { url = new URL(url, location.href); }
catch (error) {
API.log(`checkURL ${url} ➜ ${error.message}`);
return;
}
// check protocol
if (!['http:', 'https:', 'blob:'].includes(url.protocol)) {
API.log(`checkURL ${url} ➜ Unsupported Protocol ${url.protocol}`);
return;
}
return url.href;
}
// --- prepare request headers
static prepareInit(init) {
// --- remove forbidden headers (Attempt to set a forbidden header was denied: Referer), allow specialHeader
const specialHeader = ['cookie', 'host', 'origin', 'referer'];
const forbiddenHeader = ['accept-charset', 'accept-encoding', 'access-control-request-headers',
'access-control-request-method', 'connection', 'content-length', 'cookie2', 'date', 'dnt', 'expect',
'keep-alive', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'via'];
init.headers ||= {}; // check init.headers
Object.keys(init.headers).forEach(item => {
const LC = item.toLowerCase();
if (LC.startsWith('proxy-') || LC.startsWith('sec-') || forbiddenHeader.includes(LC)) {
delete init.headers[item];
}
else if (specialHeader.includes(LC)) {
const name = LC.charAt(0).toUpperCase() + LC.substring(1); // fix case
init.headers[item] && (init.headers[`FM-${name}`] = init.headers[item]); // set a new FM header
delete init.headers[item]; // delete original header
}
});
delete init.anonymous; // clean up
}
// ---------- import -----------------------------------
// Support loading content scripts as ES6 modules
// https://bugzilla.mozilla.org/show_bug.cgi?id=1451545
// GM.import() -> importBridge()
// internal modules && images
// get response.blob() with original type
static async importBridge(url) {
// --- internal module
const mod = {
PSL: `${FMUrl}content/psl.js`
};
if (mod[url]) {
return fetch(mod[url])
.then(response => response.blob())
.then(blob => URL.createObjectURL(blob));
}
// --- remote import
url = API.checkURL(url);
if (!url) { return; }
return GM.fetch(url, {responseType: 'blob'})
.then(response => response?.blob && URL.createObjectURL(response.blob));
}
// ---------- /import ----------------------------------
// ---------- xmlHttpRequest callback ------------------
/*
Ref: Rob Wu (robwu)
In order to make callback functions visible
ONLY for GM.xmlHttpRequest(GM_xmlhttpRequest)
*/
static userScriptCallback(object, name, ...args) {
try {
const cb = object.wrappedJSObject[name];
typeof cb === 'function' && cb(...args);
}
catch (error) {
API.log(`userScriptCallback ➜ ${error.message}`);
}
}
}
// ---------- GM4 Object based functions -----------------
const GM = {
// ---------- storage ----------------------------------
async getValue(key, defaultValue) {
const data = await API.getData();
return API.getStorageValue(data.storage, key, defaultValue);
},
// based on browser.storage.local.set()
// An object containing one or more key/value pairs to be stored in storage.
// If an item already exists, its value will be updated.
async setValue(key, value) {
if (!key) { return; }
const obj = typeof key === 'string' ? {[key]: value} : key; // change to object
// update sync storage
Object.entries(obj).forEach(([key, value]) => storage[key] = value);
// update async storage
return browser.runtime.sendMessage({
api: 'setValue',
name,
data: obj
});
},
// based on browser.storage.local.remove()
// A string, or array of strings, representing the key(s) of the item(s) to be removed.
async deleteValue(key) {
if (!key) { return; }
const arr = Array.isArray(key) ? key : [key]; // change to array
// update sync storage
arr.forEach(i => delete storage[i]);
// update async storage
return browser.runtime.sendMessage({
api: 'deleteValue',
name,
data: arr
});
},
async listValues() {
const data = await API.getData();
const value = Object.keys(data.storage);
return script.export(value);
},
addValueChangeListener(key, callback) {
browser.storage.onChanged.addListener(API.onChanged);
valueChange[key] = callback;
return key;
},
removeValueChangeListener(key) {
delete valueChange[key];
},
// ---------- /storage ---------------------------------
// ---------- other background functions ---------------
download(url, filename) {
// --- check url
url = API.checkURL(url);
if (!url) { return Promise.reject(); }
return browser.runtime.sendMessage({
api: 'download',
name,
data: {url, filename}
});
},
notification(text, title, image, onclick) {
// GM|TM|VM: (text, title, image, onclick)
// TM|VM: {text, title, image, onclick}
const txt = text?.text || text;
if (typeof txt !== 'string' || !txt.trim()) { return; }
return browser.runtime.sendMessage({
api: 'notification',
name,
data: typeof text === 'string' ? {text, title, image, onclick} : text
});
},
// opt = open_in_background
async openInTab(url, opt) {
// GM opt: boolean
// TM|VM opt: boolean OR object {active: true/false}
const active = typeof opt === 'object' ? !!opt.active : !opt;
// Error: Return value not accessible to the userScript
// resolve -> tab object | reject -> undefined
const tab = await browser.runtime.sendMessage({
api: 'openInTab',
name,
data: {url, active}
});
return !!tab; // true/false
},
// As the API is only available to Secure Contexts, it cannot be used from
// a content script running on http:-pages, only https:-pages.
// See also: https://github.com/w3c/webextensions/issues/378
setClipboard(data, type) {
// VM type: string MIME type e.g. 'text/plain'
// TM type: string e.g. 'text' or 'html'
// TM type: object e.g. {type: 'text', mimetype: 'text/plain'}
type = type?.mimetype || type?.type || type || 'text/plain'; // defaults to 'text/plain'
// fix short type
if (type === 'text') { type = 'text/plain'; }
else if (type === 'html') { type = 'text/html'; }
return browser.runtime.sendMessage({
api: 'setClipboard',
name,
data: {data, type}
});
},
async fetch(url, init = {}) {
// check url
url &&= API.checkURL(url);
if (!url) { return; }
const data = {
url,
init: {headers: {}}
};
['method', 'headers', 'body', 'mode', 'credentials', 'cache', 'redirect',
'referrer', 'referrerPolicy', 'integrity', 'keepalive', 'signal',
'responseType'].forEach(i => Object.hasOwn(init, i) && (data.init[i] = init[i]));
// exclude credentials in request, ignore credentials sent back in response (e.g. Set-Cookie header)
init.anonymous && (data.init.credentials = 'omit');
API.prepareInit(data.init);
const response = await browser.runtime.sendMessage({
api: 'fetch',
name,
data
});
// cloneInto() work around for https://bugzilla.mozilla.org/show_bug.cgi?id=1583159
return response ? cloneInto(response, window) : undefined;
},
async xmlHttpRequest(init = {}) {
// check url
const url = init.url && API.checkURL(init.url);
if (!url) { return; }
const data = {
method: 'GET',
url,
data: null,
user: null,
password: null,
responseType: '',
headers: {},
mozAnon: !!init.anonymous
};
// not processing withCredentials as it has no effect from bg script
['method', 'headers', 'data', 'overrideMimeType', 'user', 'password', 'timeout',
'responseType'].forEach(i => Object.hasOwn(init, i) && (data[i] = init[i]));
API.prepareInit(data);
const response = await browser.runtime.sendMessage({
api: 'xmlHttpRequest',
name,
data
});
if (!response) { throw 'There was an error with the xmlHttpRequest request.'; }
// only these 4 callback functions are processed
// cloneInto() work around for https://bugzilla.mozilla.org/show_bug.cgi?id=1583159
const type = response.type;
delete response.type;
// convert text responseXML to XML DocumentFragment
response.responseXML &&= document.createRange().createContextualFragment(response.responseXML.trim());
API.userScriptCallback(init, type,
typeof response.response === 'string' ? script.export(response) : cloneInto(response, window));
},
// ---------- /other background functions --------------
// ---------- DOM functions ----------------------------
addStyle(str) {
str.trim() && GM.addElement('style', {textContent: str});
},
addScript(str) {
str.trim() && GM.addElement('script', {textContent: str});
},
addElement(parent, tag, attr) {
if (!parent || !tag) { return; }
// mapping (tagName, attributes) vs (parentElement, tagName, attributes)
let parentElement = attr && parent;
const tagName = (attr ? tag : parent).toLowerCase();
const attributes = attr || tag;
const script = tagName === 'script';
switch (true) {
case !!parentElement:
break;
case ['link', 'meta'].includes(tagName):
parentElement = document.head || document.body;
break;
case ['script', 'style'].includes(tagName):
parentElement = document.head || document.body || document.documentElement || document;
break;
default:
parentElement = document.body || document.documentElement || document;
}
const elem = document.createElement(tagName);
elem.dataset.src = `${name}.user.js`;
Object.entries(attributes)?.forEach(([key, value]) =>
key === 'textContent' ? elem.append(value) : elem.setAttribute(key, value));
// script only
if (script && attributes.textContent && injectInto !== 'page') {
elem.textContent +=
`\n\n//# sourceURL=${FMUrl}userscript/${encodeURI(name)}/inject-into-page/${Math.random().toString(36).substring(2)}.js`;
}
try {
const el = parentElement.appendChild(elem);
script && el.remove();
// userscript may record UUID in element's textContent
return script ? undefined : elem;
}
catch (error) { API.log(`addElement ➜ ${tagName} ${error.message}`); }
},
popup({type = 'center', modal = true} = {}) {
const host = document.createElement('gm-popup'); // shadow DOM host
const shadow = host.attachShadow({mode: 'closed'}); // closed: inaccessible from the outside
const style = document.createElement('style');
style.textContent = `@import "${FMUrl}content/api-popup.css";`;
shadow.appendChild(style);
const content = document.createElement('div'); // main content
content.className = 'content';
shadow.appendChild(content);
const close = document.createElement('span'); // close button
close.className = 'close';
close.textContent = '✖';
content.appendChild(close);
[host, content].forEach(i => i.classList.add(type)); // process options
host.classList.toggle('modal', type.startsWith('panel-') ? modal : true); // process modal
document.body.appendChild(host);
const obj = {
host,
style,
content,
close,
addStyle(css) {
style.textContent += '\n\n' + css;
},
append(...arg) {
typeof arg[0] === 'string' && /^<.+>$/.test(arg[0].trim()) ?
content.append(document.createRange().createContextualFragment(arg[0].trim())) :
content.append(...arg);
},
show() {
host.style.opacity = 1;
host.classList.add('on');
},
hide(e) {
if (!e || [host, close].includes(e.originalTarget)) {
host.style.opacity = 0;
setTimeout(() => host.classList.remove('on'), 500);
}
},
remove() {
host.remove();
}
};
host.addEventListener('click', obj.hide);
return script.export(obj);
},
// ---------- /DOM functions ---------------------------
// ---------- import -----------------------------------
createObjectURL(val, option = {type: 'text/javascript'}) {
const blob = new Blob([val], {type: option.type});
return URL.createObjectURL(blob);
},
// ---------- /import ----------------------------------
// --- async promise return GM.getResourceText
async getResourceText(resourceName) {
return resourceData[resourceName] || '';
},
// --- async Promise return GM.getResourceUrl
async getResourceUrl(resourceName) {
return resources[resourceName];
},
registerMenuCommand(text, onclick, accessKey) {
scriptCommand[text] = onclick;
},
unregisterMenuCommand(text) {
delete scriptCommand[text];
},
log(...text) {
// eslint-disable-next-line no-console
console.log(`${name}:`, ...text);
},
info,
};
/* eslint-disable @stylistic/js/key-spacing */
const globals = {
GM,
// background functions
GM_download: GM.download,
GM_fetch: GM.fetch,
GM_notification: GM.notification,
GM_openInTab: GM.openInTab,
GM_setClipboard: GM.setClipboard,
GM_xmlhttpRequest: GM.xmlHttpRequest, // http -> Http
// Storage
GM_getValue: API.GM_getValue,
GM_setValue: GM.setValue,
GM_deleteValue: GM.deleteValue,
GM_listValues: API.GM_listValues,
// DOM functions
GM_addElement: GM.addElement,
GM_addScript: GM.addScript,
GM_addStyle: GM.addStyle,
GM_popup: GM.popup,
// other
GM_getResourceText: API.GM_getResourceText,
GM_getResourceURL: API.getResourceUrl, // URL -> Url
GM_addValueChangeListener: GM.addValueChangeListener,
GM_removeValueChangeListener: GM.removeValueChangeListener,
GM_registerMenuCommand: GM.registerMenuCommand,
GM_unregisterMenuCommand: GM.unregisterMenuCommand,
GM_createObjectURL: GM.createObjectURL,
GM_info: GM.info,
GM_log: GM.log,
// Firefox functions
cloneInto: API.cloneIntoBridge,
exportFunction,
// internal use
matchURL: API.matchURL,
setStorage: API.setStorage,
importBridge: API.importBridge,
injectIntoPage: API.injectIntoPage,
};
// auto-disable sync GM API if async GM API are granted
grantRemove.forEach(i => delete globals[i]);
// --- check @require CSS
remoteCSS.forEach(i => GM.addElement('link', {href: i, rel: 'stylesheet'}));
script.defineGlobals(globals);
});