2020-02-24 23:16:45 +00:00
|
|
|
/* exported getTab getActiveTab onTabReady stringAsRegExp openURL ignoreChromeError
|
2019-09-25 08:44:33 +00:00
|
|
|
getStyleWithNoCode tryRegExp sessionStorageHash download deepEqual
|
2020-02-02 04:36:54 +00:00
|
|
|
closeCurrentTab capitalize CHROME_HAS_BORDER_BUG */
|
|
|
|
/* global promisify */
|
2017-07-12 18:17:04 +00:00
|
|
|
'use strict';
|
|
|
|
|
2017-11-14 07:52:54 +00:00
|
|
|
const CHROME = Boolean(chrome.app) && parseInt(navigator.userAgent.match(/Chrom\w+\/(?:\d+\.){2}(\d+)|$/)[1]);
|
2018-01-01 17:02:49 +00:00
|
|
|
const OPERA = Boolean(chrome.app) && parseFloat(navigator.userAgent.match(/\bOPR\/(\d+\.\d+)|$/)[1]);
|
|
|
|
const VIVALDI = Boolean(chrome.app) && navigator.userAgent.includes('Vivaldi');
|
2018-11-07 06:09:29 +00:00
|
|
|
// FIXME: who use this?
|
|
|
|
// const ANDROID = !chrome.windows;
|
2018-01-01 17:02:49 +00:00
|
|
|
let FIREFOX = !chrome.app && parseFloat(navigator.userAgent.match(/\bFirefox\/(\d+\.\d+)|$/)[1]);
|
2017-11-08 03:46:56 +00:00
|
|
|
|
2019-09-24 13:21:36 +00:00
|
|
|
// see PR #781
|
|
|
|
const CHROME_HAS_BORDER_BUG = CHROME >= 3167 && CHROME <= 3704;
|
|
|
|
|
2017-11-14 07:52:54 +00:00
|
|
|
if (!CHROME && !chrome.browserAction.openPopup) {
|
2017-11-08 03:46:56 +00:00
|
|
|
// in FF pre-57 legacy addons can override useragent so we assume the worst
|
|
|
|
// until we know for sure in the async getBrowserInfo()
|
|
|
|
// (browserAction.openPopup was added in 57)
|
2018-02-25 13:51:07 +00:00
|
|
|
FIREFOX = browser.runtime.getBrowserInfo ? 51 : 50;
|
|
|
|
// getBrowserInfo was added in FF 51
|
|
|
|
Promise.resolve(FIREFOX >= 51 ? browser.runtime.getBrowserInfo() : {version: 50}).then(info => {
|
2017-11-08 03:46:56 +00:00
|
|
|
FIREFOX = parseFloat(info.version);
|
2017-12-04 16:14:04 +00:00
|
|
|
document.documentElement.classList.add('moz-appearance-bug', FIREFOX && FIREFOX < 54);
|
2017-11-08 03:46:56 +00:00
|
|
|
});
|
|
|
|
}
|
2017-07-12 18:17:04 +00:00
|
|
|
|
|
|
|
const URLS = {
|
|
|
|
ownOrigin: chrome.runtime.getURL(''),
|
|
|
|
|
2020-02-02 04:36:54 +00:00
|
|
|
// FIXME delete?
|
2017-07-12 18:17:04 +00:00
|
|
|
optionsUI: [
|
2017-07-14 08:25:33 +00:00
|
|
|
chrome.runtime.getURL('options.html'),
|
2017-07-12 18:17:04 +00:00
|
|
|
'chrome://extensions/?options=' + chrome.runtime.id,
|
|
|
|
],
|
|
|
|
|
|
|
|
configureCommands:
|
|
|
|
OPERA ? 'opera://settings/configureCommands'
|
|
|
|
: 'chrome://extensions/configureCommands',
|
|
|
|
|
2020-02-23 15:43:26 +00:00
|
|
|
installUsercss: chrome.runtime.getURL('install-usercss.html'),
|
|
|
|
|
2017-07-12 18:17:04 +00:00
|
|
|
// CWS cannot be scripted in chromium, see ChromeExtensionsClient::IsScriptableURL
|
|
|
|
// https://cs.chromium.org/chromium/src/chrome/common/extensions/chrome_extensions_client.cc
|
2017-07-22 16:52:07 +00:00
|
|
|
browserWebStore:
|
|
|
|
FIREFOX ? 'https://addons.mozilla.org/' :
|
|
|
|
OPERA ? 'https://addons.opera.com/' :
|
|
|
|
'https://chrome.google.com/webstore/',
|
|
|
|
|
2018-03-30 00:23:21 +00:00
|
|
|
emptyTab: [
|
|
|
|
// Chrome and simple forks
|
|
|
|
'chrome://newtab/',
|
|
|
|
// Opera
|
|
|
|
'chrome://startpage/',
|
|
|
|
// Vivaldi
|
|
|
|
'chrome-extension://mpognobbkildjkofajifpdfhcoklimli/components/startpage/startpage.html',
|
|
|
|
// Firefox
|
|
|
|
'about:home',
|
|
|
|
'about:newtab',
|
|
|
|
],
|
|
|
|
|
2017-07-22 16:52:07 +00:00
|
|
|
// Chrome 61.0.3161+ doesn't run content scripts on NTP https://crrev.com/2978953002/
|
|
|
|
// TODO: remove when "minimum_chrome_version": "61" or higher
|
2017-11-14 07:52:54 +00:00
|
|
|
chromeProtectsNTP: CHROME >= 3161,
|
2017-07-22 16:52:07 +00:00
|
|
|
|
2018-04-12 06:13:31 +00:00
|
|
|
userstylesOrgJson: 'https://userstyles.org/styles/chrome/',
|
|
|
|
|
2017-08-16 17:40:24 +00:00
|
|
|
supported: url => (
|
2017-12-22 05:36:10 +00:00
|
|
|
url.startsWith('http') && (FIREFOX || !url.startsWith(URLS.browserWebStore)) ||
|
2017-08-16 17:40:24 +00:00
|
|
|
url.startsWith('ftp') ||
|
|
|
|
url.startsWith('file') ||
|
|
|
|
url.startsWith(URLS.ownOrigin) ||
|
|
|
|
!URLS.chromeProtectsNTP && url.startsWith('chrome://newtab/')
|
|
|
|
),
|
2017-07-12 18:17:04 +00:00
|
|
|
};
|
|
|
|
|
2018-11-07 06:09:29 +00:00
|
|
|
const IS_BG = chrome.extension.getBackgroundPage && chrome.extension.getBackgroundPage() === window;
|
|
|
|
|
|
|
|
if (!IS_BG) {
|
2017-12-07 03:52:43 +00:00
|
|
|
if (FIREFOX) {
|
|
|
|
document.documentElement.classList.add('firefox');
|
2017-12-07 03:54:51 +00:00
|
|
|
} else if (OPERA) {
|
2017-12-07 03:52:43 +00:00
|
|
|
document.documentElement.classList.add('opera');
|
2018-01-01 17:02:49 +00:00
|
|
|
} else {
|
|
|
|
if (VIVALDI) document.documentElement.classList.add('vivaldi');
|
2017-12-07 03:52:43 +00:00
|
|
|
}
|
2017-11-24 15:26:20 +00:00
|
|
|
}
|
|
|
|
|
2018-11-07 06:09:29 +00:00
|
|
|
if (IS_BG) {
|
|
|
|
window.API_METHODS = {};
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
|
|
|
|
2018-11-07 06:09:29 +00:00
|
|
|
// FIXME: `localStorage` and `sessionStorage` may be disabled via dom.storage.enabled
|
|
|
|
// Object.defineProperty(window, 'localStorage', {value: {}});
|
|
|
|
// Object.defineProperty(window, 'sessionStorage', {value: {}});
|
2017-07-12 18:17:04 +00:00
|
|
|
|
2020-02-02 04:36:54 +00:00
|
|
|
const createTab = promisify(chrome.tabs.create.bind(chrome.tabs));
|
|
|
|
const queryTabs = promisify(chrome.tabs.query.bind(chrome.tabs));
|
|
|
|
const updateTab = promisify(chrome.tabs.update.bind(chrome.tabs));
|
|
|
|
const moveTabs = promisify(chrome.tabs.move.bind(chrome.tabs));
|
2020-02-20 22:54:54 +00:00
|
|
|
|
|
|
|
// Android doesn't have chrome.windows
|
|
|
|
const updateWindow = chrome.windows && promisify(chrome.windows.update.bind(chrome.windows));
|
|
|
|
const createWindow = chrome.windows && promisify(chrome.windows.create.bind(chrome.windows));
|
|
|
|
// FF57+ supports openerTabId, but not in Android
|
|
|
|
// (detecting FF57 by the feature it added, not navigator.ua which may be spoofed in about:config)
|
|
|
|
const openerTabIdSupported = (!FIREFOX || window.AbortController) && chrome.windows != null;
|
2017-07-12 18:17:04 +00:00
|
|
|
|
|
|
|
function getTab(id) {
|
|
|
|
return new Promise(resolve =>
|
|
|
|
chrome.tabs.get(id, tab =>
|
|
|
|
!chrome.runtime.lastError && resolve(tab)));
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function getOwnTab() {
|
|
|
|
return new Promise(resolve =>
|
|
|
|
chrome.tabs.getCurrent(tab => resolve(tab)));
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function getActiveTab() {
|
|
|
|
return queryTabs({currentWindow: true, active: true})
|
|
|
|
.then(tabs => tabs[0]);
|
|
|
|
}
|
|
|
|
|
2020-02-02 04:36:54 +00:00
|
|
|
function urlToMatchPattern(url, ignoreSearch) {
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns
|
|
|
|
if (!/^(http|https|ws|wss|ftp|data|file)$/.test(url.protocol)) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
if (ignoreSearch) {
|
|
|
|
return [
|
|
|
|
`${url.protocol}//${url.hostname}/${url.pathname}`,
|
|
|
|
`${url.protocol}//${url.hostname}/${url.pathname}?*`
|
|
|
|
];
|
|
|
|
}
|
|
|
|
// FIXME: is %2f allowed in pathname and search?
|
|
|
|
return `${url.protocol}//${url.hostname}/${url.pathname}${url.search}`;
|
|
|
|
}
|
|
|
|
|
2020-02-20 22:54:54 +00:00
|
|
|
function findExistingTab({url, currentWindow, ignoreHash = true, ignoreSearch = false}) {
|
2020-02-02 04:36:54 +00:00
|
|
|
url = new URL(url);
|
|
|
|
return queryTabs({url: urlToMatchPattern(url, ignoreSearch), currentWindow})
|
|
|
|
// FIXME: is tab.url always normalized?
|
|
|
|
.then(tabs => tabs.find(matchTab));
|
|
|
|
|
|
|
|
function matchTab(tab) {
|
|
|
|
const tabUrl = new URL(tab.url);
|
|
|
|
return tabUrl.protocol === url.protocol &&
|
|
|
|
tabUrl.username === url.username &&
|
|
|
|
tabUrl.password === url.password &&
|
|
|
|
tabUrl.hostname === url.hostname &&
|
|
|
|
tabUrl.port === url.port &&
|
|
|
|
tabUrl.pathname === url.pathname &&
|
|
|
|
(ignoreSearch || tabUrl.search === url.search) &&
|
|
|
|
(ignoreHash || tabUrl.hash === url.hash);
|
|
|
|
}
|
|
|
|
}
|
2018-03-14 02:58:28 +00:00
|
|
|
|
2017-12-31 14:58:35 +00:00
|
|
|
/**
|
|
|
|
* Opens a tab or activates an existing one,
|
|
|
|
* reuses the New Tab page or about:blank if it's focused now
|
2020-02-20 22:54:54 +00:00
|
|
|
* @param {Object} _
|
|
|
|
* @param {string} _.url - if relative, it's auto-expanded to the full extension URL
|
|
|
|
* @param {number} [_.index] move the tab to this index in the tab strip, -1 = last
|
|
|
|
* @param {number} [_.openerTabId] defaults to the active tab
|
|
|
|
* @param {Boolean} [_.active=true] `true` to activate the tab
|
|
|
|
* @param {Boolean|null} [_.currentWindow=true] `null` to check all windows
|
|
|
|
* @param {Boolean} [_.newWindow=false] `true` to open a new window
|
|
|
|
* @param {chrome.windows.CreateData} [_.windowPosition] options for chrome.windows.create
|
|
|
|
* @returns {Promise<chrome.tabs.Tab>} Promise -> opened/activated tab
|
2017-12-31 14:58:35 +00:00
|
|
|
*/
|
2020-02-20 22:54:54 +00:00
|
|
|
function openURL({
|
|
|
|
url,
|
|
|
|
index,
|
|
|
|
openerTabId,
|
|
|
|
active = true,
|
|
|
|
currentWindow = true,
|
|
|
|
newWindow = false,
|
|
|
|
windowPosition,
|
|
|
|
}) {
|
2020-02-02 04:36:54 +00:00
|
|
|
if (!url.includes('://')) {
|
|
|
|
url = chrome.runtime.getURL(url);
|
|
|
|
}
|
2020-02-20 22:54:54 +00:00
|
|
|
return findExistingTab({url, currentWindow}).then(tab => {
|
2020-02-02 04:36:54 +00:00
|
|
|
if (tab) {
|
2020-02-20 22:54:54 +00:00
|
|
|
return activateTab(tab, {
|
|
|
|
index,
|
|
|
|
openerTabId,
|
|
|
|
// when hash is different we can only set `url` if it has # otherwise the tab would reload
|
|
|
|
url: url !== tab.url && url.includes('#') ? url : undefined,
|
|
|
|
});
|
2017-12-31 14:58:35 +00:00
|
|
|
}
|
2020-02-20 22:54:54 +00:00
|
|
|
if (newWindow && createWindow) {
|
|
|
|
return createWindow(Object.assign({url}, windowPosition))
|
|
|
|
.then(wnd => wnd.tabs[0]);
|
2017-12-31 14:58:35 +00:00
|
|
|
}
|
2020-02-20 22:54:54 +00:00
|
|
|
return getActiveTab().then((activeTab = {url: ''}) =>
|
|
|
|
isTabReplaceable(activeTab, url) ?
|
|
|
|
activateTab(activeTab, {url, openerTabId}) : // not moving the tab
|
|
|
|
createTabWithOpener(activeTab, {url, index, active}));
|
2020-02-02 04:36:54 +00:00
|
|
|
});
|
2020-02-20 22:54:54 +00:00
|
|
|
function createTabWithOpener(openerTab, options) {
|
|
|
|
const id = openerTabId == null ? openerTab.id : openerTabId;
|
|
|
|
if (id != null && !openerTab.incognito && openerTabIdSupported) {
|
|
|
|
options.openerTabId = id;
|
|
|
|
}
|
|
|
|
return createTab(options);
|
|
|
|
}
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
|
|
|
|
2020-02-02 04:36:54 +00:00
|
|
|
// replace empty tab (NTP or about:blank)
|
|
|
|
// except when new URL is chrome:// or chrome-extension:// and the empty tab is
|
|
|
|
// in incognito
|
|
|
|
function isTabReplaceable(tab, newUrl) {
|
|
|
|
if (!tab || !URLS.emptyTab.includes(tab.url)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
// FIXME: but why?
|
|
|
|
if (tab.incognito && newUrl.startsWith('chrome')) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
2017-07-12 18:17:04 +00:00
|
|
|
|
2020-02-20 22:54:54 +00:00
|
|
|
function activateTab(tab, {url, index, openerTabId} = {}) {
|
2020-02-02 04:36:54 +00:00
|
|
|
const options = {active: true};
|
|
|
|
if (url) {
|
|
|
|
options.url = url;
|
|
|
|
}
|
2020-02-20 22:54:54 +00:00
|
|
|
if (openerTabId != null && openerTabIdSupported) {
|
|
|
|
options.openerTabId = openerTabId;
|
|
|
|
}
|
2017-07-12 18:17:04 +00:00
|
|
|
return Promise.all([
|
2020-02-02 04:36:54 +00:00
|
|
|
updateTab(tab.id, options),
|
2020-02-20 22:54:54 +00:00
|
|
|
updateWindow && updateWindow(tab.windowId, {focused: true}),
|
2020-02-02 04:36:54 +00:00
|
|
|
index != null && moveTabs(tab.id, {index})
|
|
|
|
])
|
|
|
|
.then(() => tab);
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function stringAsRegExp(s, flags) {
|
2017-07-22 16:52:07 +00:00
|
|
|
return new RegExp(s.replace(/[{}()[\]\\.+*?^$|]/g, '\\$&'), flags);
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function ignoreChromeError() {
|
2017-12-18 06:57:00 +00:00
|
|
|
// eslint-disable-next-line no-unused-expressions
|
|
|
|
chrome.runtime.lastError;
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function getStyleWithNoCode(style) {
|
2018-01-01 17:02:49 +00:00
|
|
|
const stripped = deepCopy(style);
|
|
|
|
for (const section of stripped.sections) section.code = null;
|
|
|
|
stripped.sourceCode = null;
|
2017-07-12 18:17:04 +00:00
|
|
|
return stripped;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// js engine can't optimize the entire function if it contains try-catch
|
|
|
|
// so we should keep it isolated from normal code in a minimal wrapper
|
|
|
|
// Update: might get fixed in V8 TurboFan in the future
|
|
|
|
function tryCatch(func, ...args) {
|
|
|
|
try {
|
|
|
|
return func(...args);
|
|
|
|
} catch (e) {}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2017-12-06 06:39:45 +00:00
|
|
|
function tryRegExp(regexp, flags) {
|
2017-07-12 18:17:04 +00:00
|
|
|
try {
|
2017-12-06 06:39:45 +00:00
|
|
|
return new RegExp(regexp, flags);
|
2017-07-12 18:17:04 +00:00
|
|
|
} catch (e) {}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function tryJSONparse(jsonString) {
|
|
|
|
try {
|
|
|
|
return JSON.parse(jsonString);
|
|
|
|
} catch (e) {}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const debounce = Object.assign((fn, delay, ...args) => {
|
|
|
|
clearTimeout(debounce.timers.get(fn));
|
|
|
|
debounce.timers.set(fn, setTimeout(debounce.run, delay, fn, ...args));
|
|
|
|
}, {
|
|
|
|
timers: new Map(),
|
|
|
|
run(fn, ...args) {
|
|
|
|
debounce.timers.delete(fn);
|
|
|
|
fn(...args);
|
|
|
|
},
|
|
|
|
unregister(fn) {
|
|
|
|
clearTimeout(debounce.timers.get(fn));
|
|
|
|
debounce.timers.delete(fn);
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
function deepCopy(obj) {
|
2018-01-01 17:02:49 +00:00
|
|
|
if (!obj || typeof obj !== 'object') return obj;
|
2018-01-10 18:56:14 +00:00
|
|
|
// N.B. the copy should be an explicit literal
|
2018-01-01 17:02:49 +00:00
|
|
|
if (Array.isArray(obj)) {
|
|
|
|
const copy = [];
|
|
|
|
for (const v of obj) {
|
|
|
|
copy.push(!v || typeof v !== 'object' ? v : deepCopy(v));
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
2018-01-01 17:02:49 +00:00
|
|
|
return copy;
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
2018-01-01 17:02:49 +00:00
|
|
|
const copy = {};
|
|
|
|
const hasOwnProperty = Object.prototype.hasOwnProperty;
|
|
|
|
for (const k in obj) {
|
|
|
|
if (!hasOwnProperty.call(obj, k)) continue;
|
|
|
|
const v = obj[k];
|
|
|
|
copy[k] = !v || typeof v !== 'object' ? v : deepCopy(v);
|
|
|
|
}
|
|
|
|
return copy;
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-09-25 08:44:33 +00:00
|
|
|
function deepEqual(a, b, ignoredKeys) {
|
|
|
|
if (!a || !b) return a === b;
|
|
|
|
const type = typeof a;
|
|
|
|
if (type !== typeof b) return false;
|
|
|
|
if (type !== 'object') return a === b;
|
|
|
|
if (Array.isArray(a)) {
|
|
|
|
return Array.isArray(b) &&
|
|
|
|
a.length === b.length &&
|
|
|
|
a.every((v, i) => deepEqual(v, b[i], ignoredKeys));
|
|
|
|
}
|
|
|
|
for (const key in a) {
|
|
|
|
if (!Object.hasOwnProperty.call(a, key) ||
|
|
|
|
ignoredKeys && ignoredKeys.includes(key)) continue;
|
|
|
|
if (!Object.hasOwnProperty.call(b, key)) return false;
|
|
|
|
if (!deepEqual(a[key], b[key], ignoredKeys)) return false;
|
|
|
|
}
|
|
|
|
for (const key in b) {
|
|
|
|
if (!Object.hasOwnProperty.call(b, key) ||
|
|
|
|
ignoredKeys && ignoredKeys.includes(key)) continue;
|
|
|
|
if (!Object.hasOwnProperty.call(a, key)) return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2017-07-12 18:17:04 +00:00
|
|
|
function sessionStorageHash(name) {
|
|
|
|
return {
|
|
|
|
name,
|
|
|
|
value: tryCatch(JSON.parse, sessionStorage[name]) || {},
|
|
|
|
set(k, v) {
|
|
|
|
this.value[k] = v;
|
|
|
|
this.updateStorage();
|
|
|
|
},
|
|
|
|
unset(k) {
|
|
|
|
delete this.value[k];
|
|
|
|
this.updateStorage();
|
|
|
|
},
|
|
|
|
updateStorage() {
|
|
|
|
sessionStorage[this.name] = JSON.stringify(this.value);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2018-03-12 18:41:25 +00:00
|
|
|
/**
|
|
|
|
* @param {String} url
|
|
|
|
* @param {Object} params
|
|
|
|
* @param {String} [params.method]
|
|
|
|
* @param {String|Object} [params.body]
|
|
|
|
* @param {String} [params.responseType] arraybuffer, blob, document, json, text
|
|
|
|
* @param {Number} [params.requiredStatusCode] resolved when matches, otherwise rejected
|
|
|
|
* @param {Number} [params.timeout] ms
|
|
|
|
* @param {Object} [params.headers] {name: value}
|
|
|
|
* @returns {Promise}
|
|
|
|
*/
|
2017-11-24 19:30:39 +00:00
|
|
|
function download(url, {
|
2018-03-12 18:41:25 +00:00
|
|
|
method = 'GET',
|
2018-03-12 19:39:19 +00:00
|
|
|
body,
|
2017-12-10 07:05:47 +00:00
|
|
|
responseType = 'text',
|
2017-11-24 19:30:39 +00:00
|
|
|
requiredStatusCode = 200,
|
2020-05-16 19:50:04 +00:00
|
|
|
timeout = 10e3, // connection timeout
|
|
|
|
loadTimeout = 2 * 60e3, // data transfer timeout (counted from the first remote response)
|
2017-11-24 19:30:39 +00:00
|
|
|
headers = {
|
|
|
|
'Content-type': 'application/x-www-form-urlencoded',
|
|
|
|
},
|
|
|
|
} = {}) {
|
2018-03-12 18:41:25 +00:00
|
|
|
const queryPos = url.indexOf('?');
|
2018-03-12 19:39:19 +00:00
|
|
|
if (queryPos > 0 && body === undefined) {
|
2018-03-12 18:41:25 +00:00
|
|
|
method = 'POST';
|
|
|
|
body = url.slice(queryPos);
|
|
|
|
url = url.slice(0, queryPos);
|
|
|
|
}
|
2018-04-12 06:13:31 +00:00
|
|
|
// * USO can't handle POST requests for style json
|
|
|
|
// * XHR/fetch can't handle long URL
|
|
|
|
// So we need to collapse all long variables and expand them in the response
|
|
|
|
const usoVars = [];
|
|
|
|
|
2017-07-12 18:17:04 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2020-05-16 19:50:04 +00:00
|
|
|
let xhr;
|
2018-04-12 06:13:31 +00:00
|
|
|
const u = new URL(collapseUsoVars(url));
|
2020-05-16 19:50:04 +00:00
|
|
|
const onTimeout = () => {
|
|
|
|
if (xhr) xhr.abort();
|
|
|
|
reject(new Error('Timeout fetching ' + u.href));
|
|
|
|
};
|
|
|
|
let timer = setTimeout(onTimeout, timeout);
|
|
|
|
const switchTimer = () => {
|
|
|
|
clearTimeout(timer);
|
|
|
|
timer = loadTimeout && setTimeout(onTimeout, loadTimeout);
|
|
|
|
};
|
|
|
|
if (u.protocol === 'file:' && FIREFOX) { // TODO: maybe remove this since FF68+ can't do it anymore
|
2017-09-18 22:50:20 +00:00
|
|
|
// https://stackoverflow.com/questions/42108782/firefox-webextensions-get-local-files-content-by-path
|
|
|
|
// FIXME: add FetchController when it is available.
|
2018-04-12 06:13:31 +00:00
|
|
|
fetch(u.href, {mode: 'same-origin'})
|
2017-09-18 22:50:20 +00:00
|
|
|
.then(r => {
|
2020-05-16 19:50:04 +00:00
|
|
|
switchTimer();
|
2017-11-24 19:30:39 +00:00
|
|
|
return r.status === 200 ? r.text() : Promise.reject(r.status);
|
2017-09-18 22:50:20 +00:00
|
|
|
})
|
2017-11-24 19:30:39 +00:00
|
|
|
.catch(reject)
|
2020-05-16 19:50:04 +00:00
|
|
|
.then(text => {
|
|
|
|
clearTimeout(timer);
|
|
|
|
resolve(text);
|
|
|
|
});
|
2017-09-18 22:50:20 +00:00
|
|
|
return;
|
|
|
|
}
|
2020-05-16 19:50:04 +00:00
|
|
|
xhr = new XMLHttpRequest();
|
|
|
|
xhr.onreadystatechange = () => {
|
|
|
|
if (xhr.readyState >= XMLHttpRequest.HEADERS_RECEIVED) {
|
|
|
|
xhr.onreadystatechange = null;
|
|
|
|
switchTimer();
|
|
|
|
}
|
|
|
|
};
|
2017-11-24 19:30:39 +00:00
|
|
|
xhr.onloadend = event => {
|
2020-05-16 19:50:04 +00:00
|
|
|
clearTimeout(timer);
|
2017-11-24 19:30:39 +00:00
|
|
|
if (event.type !== 'error' && (
|
|
|
|
xhr.status === requiredStatusCode || !requiredStatusCode ||
|
2018-04-12 06:13:31 +00:00
|
|
|
u.protocol === 'file:')) {
|
|
|
|
resolve(expandUsoVars(xhr.response));
|
2017-11-24 19:30:39 +00:00
|
|
|
} else {
|
|
|
|
reject(xhr.status);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
xhr.onerror = xhr.onloadend;
|
2017-12-10 07:05:47 +00:00
|
|
|
xhr.responseType = responseType;
|
2018-04-12 06:13:31 +00:00
|
|
|
xhr.open(method, u.href, true);
|
2017-11-24 19:30:39 +00:00
|
|
|
for (const key in headers) {
|
|
|
|
xhr.setRequestHeader(key, headers[key]);
|
2017-09-18 22:50:20 +00:00
|
|
|
}
|
2017-11-24 19:30:39 +00:00
|
|
|
xhr.send(body);
|
2017-07-12 18:17:04 +00:00
|
|
|
});
|
2018-04-12 06:13:31 +00:00
|
|
|
|
|
|
|
function collapseUsoVars(url) {
|
|
|
|
if (queryPos < 0 ||
|
|
|
|
url.length < 2000 ||
|
|
|
|
!url.startsWith(URLS.userstylesOrgJson) ||
|
|
|
|
!/^get$/i.test(method)) {
|
|
|
|
return url;
|
|
|
|
}
|
|
|
|
const params = new URLSearchParams(url.slice(queryPos + 1));
|
|
|
|
for (const [k, v] of params.entries()) {
|
|
|
|
if (v.length < 10 || v.startsWith('ik-')) continue;
|
|
|
|
usoVars.push(v);
|
|
|
|
params.set(k, `\x01${usoVars.length}\x02`);
|
|
|
|
}
|
|
|
|
return url.slice(0, queryPos + 1) + params.toString();
|
|
|
|
}
|
|
|
|
|
|
|
|
function expandUsoVars(response) {
|
|
|
|
if (!usoVars.length || !response) return response;
|
|
|
|
const isText = typeof response === 'string';
|
|
|
|
const json = isText && tryJSONparse(response) || response;
|
|
|
|
json.updateUrl = url;
|
|
|
|
for (const section of json.sections || []) {
|
|
|
|
const {code} = section;
|
|
|
|
if (code.includes('\x01')) {
|
|
|
|
section.code = code.replace(/\x01(\d+)\x02/g, (_, num) => usoVars[num - 1] || '');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return isText ? JSON.stringify(json) : json;
|
|
|
|
}
|
2017-07-12 18:17:04 +00:00
|
|
|
}
|
|
|
|
|
2017-09-25 10:43:55 +00:00
|
|
|
function closeCurrentTab() {
|
2017-11-09 04:49:37 +00:00
|
|
|
// https://bugzilla.mozilla.org/show_bug.cgi?id=1409375
|
|
|
|
getOwnTab().then(tab => {
|
2017-09-25 10:43:55 +00:00
|
|
|
if (tab) {
|
|
|
|
chrome.tabs.remove(tab.id);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2019-11-05 19:30:45 +00:00
|
|
|
|
|
|
|
function capitalize(s) {
|
|
|
|
return s[0].toUpperCase() + s.slice(1);
|
|
|
|
}
|