stylus/background/background.js

450 lines
14 KiB
JavaScript
Raw Normal View History

2018-01-01 17:02:49 +00:00
/*
2018-02-16 15:05:25 +00:00
global handleCssTransitionBug detectSloppyRegexps
global openEditor
global styleViaAPI
global loadScript
2018-10-07 13:28:51 +00:00
global usercss styleManager db msg navigatorUtil
2018-02-16 15:05:25 +00:00
*/
'use strict';
window.API_METHODS = Object.assign(window.API_METHODS || {}, {
2018-10-04 04:46:19 +00:00
getSectionsByUrl: styleManager.getSectionsByUrl,
getSectionsById: styleManager.getSectionsById,
2018-10-04 17:03:40 +00:00
getStylesInfo: styleManager.getStylesInfo,
2018-10-05 10:47:52 +00:00
toggleStyle: styleManager.toggleStyle,
deleteStyle: styleManager.deleteStyle,
2018-10-06 05:45:37 +00:00
getStylesInfoByUrl: styleManager.getStylesInfoByUrl,
2018-10-07 14:59:31 +00:00
installStyle: styleManager.installStyle,
2018-10-10 08:14:51 +00:00
editSave: styleManager.editSave,
2018-01-01 17:02:49 +00:00
getStyleFromDB: id =>
2018-10-05 10:47:52 +00:00
db.exec('get', id).then(event => event.target.result),
download(msg) {
delete msg.method;
return download(msg.url, msg);
},
parseCss({code}) {
return usercss.invokeWorker({action: 'parse', code});
},
2018-07-05 12:42:55 +00:00
getPrefs: prefs.getAll,
2018-10-07 15:28:41 +00:00
// FIXME: who uses this?
healthCheck: () => db.exec().then(() => true),
2018-01-01 17:02:49 +00:00
detectSloppyRegexps,
openEditor,
updateIcon,
// exposed for stuff that requires followup sendMessage() like popup::openSettings
// that would fail otherwise if another extension forced the tab to open
// in the foreground thus auto-closing the popup (in Chrome)
openURL,
2018-10-07 13:20:39 +00:00
// FIXME: who use this?
2018-01-01 17:02:49 +00:00
closeTab: (msg, sender, respond) => {
chrome.tabs.remove(msg.tabId || sender.tab.id, () => {
if (chrome.runtime.lastError && msg.tabId !== sender.tab.id) {
respond(new Error(chrome.runtime.lastError.message));
}
});
2018-10-07 13:20:39 +00:00
return true;
2018-01-01 17:02:49 +00:00
},
2018-04-12 18:02:34 +00:00
optionsCustomizeHotkeys() {
return browser.runtime.openOptionsPage()
.then(() => new Promise(resolve => setTimeout(resolve, 100)))
2018-10-06 05:02:45 +00:00
.then(() => msg.broadcastExtension({method: 'optionsCustomizeHotkeys'}));
2018-04-12 18:02:34 +00:00
},
});
2018-01-01 17:02:49 +00:00
// eslint-disable-next-line no-var
var browserCommands, contextMenus;
// *************************************************************************
// register all listeners
2018-10-06 05:02:45 +00:00
msg.on(onRuntimeMessage);
if (FIREFOX) {
// see notes in apply.js for getStylesFallback
const MSG_GET_STYLES = 'getStyles:';
const MSG_GET_STYLES_LEN = MSG_GET_STYLES.length;
chrome.runtime.onConnect.addListener(port => {
if (!port.name.startsWith(MSG_GET_STYLES)) return;
const tabId = port.sender.tab.id;
const frameId = port.sender.frameId;
const options = tryJSONparse(port.name.slice(MSG_GET_STYLES_LEN));
port.disconnect();
2018-10-07 13:20:39 +00:00
// FIXME: getStylesFallback?
getStyles(options).then(styles => {
if (!styles.length) return;
chrome.tabs.executeScript(tabId, {
code: `
applyOnMessage({
method: 'styleApply',
styles: ${JSON.stringify(styles)},
})
`,
runAt: 'document_start',
frameId,
});
});
});
}
2018-10-07 13:20:39 +00:00
navigatorUtil.onUrlChange(({tabId, frameId}, type) => {
if (type === 'committed') {
// styles would be updated when content script is injected.
return;
}
2018-10-10 08:14:51 +00:00
msg.sendTab(tabId, {method: 'urlChanged'}, {frameId})
.catch(err => {
console.warn(tabId, frameId, err);
});
2018-10-07 13:20:39 +00:00
});
if (FIREFOX) {
// FF applies page CSP even to content scripts, https://bugzil.la/1267027
navigatorUtil.onCommitted(webNavUsercssInstallerFF, {
url: [
{hostSuffix: '.githubusercontent.com', urlSuffix: '.user.css'},
{hostSuffix: '.githubusercontent.com', urlSuffix: '.user.styl'},
]
});
// FF misses some about:blank iframes so we inject our content script explicitly
navigatorUtil.onDOMContentLoaded(webNavIframeHelperFF, {
url: [
{urlEquals: 'about:blank'},
]
});
}
2017-11-25 13:24:07 +00:00
if (chrome.contextMenus) {
chrome.contextMenus.onClicked.addListener((info, tab) =>
contextMenus[info.menuItemId].click(info, tab));
}
2017-11-25 13:24:07 +00:00
if (chrome.commands) {
// Not available in Firefox - https://bugzilla.mozilla.org/show_bug.cgi?id=1240350
chrome.commands.onCommand.addListener(command => browserCommands[command]());
}
2017-11-25 13:24:07 +00:00
if (!chrome.browserAction ||
!['setIcon', 'setBadgeBackgroundColor', 'setBadgeText'].every(name => chrome.browserAction[name])) {
window.updateIcon = () => {};
}
2018-01-01 17:02:49 +00:00
const tabIcons = new Map();
chrome.tabs.onRemoved.addListener(tabId => tabIcons.delete(tabId));
chrome.tabs.onReplaced.addListener((added, removed) => tabIcons.delete(removed));
// *************************************************************************
// set the default icon displayed after a tab is created until webNavigation kicks in
2018-01-01 17:02:49 +00:00
prefs.subscribe(['iconset'], () =>
updateIcon({
tab: {id: undefined},
styles: {},
}));
2018-10-07 13:28:51 +00:00
navigatorUtil.onUrlChange(({url, tabId, frameId}) => {
if (frameId === 0) {
tabIcons.delete(tabId);
updateIcon({tab: {id: tabId, url}});
}
});
2018-10-07 13:20:39 +00:00
// *************************************************************************
2018-08-06 15:20:57 +00:00
chrome.runtime.onInstalled.addListener(({reason}) => {
if (reason !== 'update') return;
// translations may change
localStorage.L10N = JSON.stringify({
browserUIlanguage: chrome.i18n.getUILanguage(),
});
// themes may change
delete localStorage.codeMirrorThemes;
});
2015-01-29 18:41:45 +00:00
// *************************************************************************
// browser commands
browserCommands = {
openManage() {
2017-07-12 18:52:44 +00:00
openURL({url: 'manage.html'});
},
styleDisableAll(info) {
prefs.set('disableAll', info ? info.checked : !prefs.get('disableAll'));
},
2017-03-18 22:35:27 +00:00
};
// *************************************************************************
2017-03-18 22:35:27 +00:00
// context menus
contextMenus = {
'show-badge': {
title: 'menuShowBadge',
click: info => prefs.set(info.menuItemId, info.checked),
},
'disableAll': {
title: 'disableAllStyles',
click: browserCommands.styleDisableAll,
},
'open-manager': {
title: 'openStylesManager',
click: browserCommands.openManage,
},
2017-04-29 16:54:16 +00:00
'editor.contextDelete': {
presentIf: () => !FIREFOX && prefs.get('editor.contextDelete'),
title: 'editDeleteText',
2017-04-29 16:54:16 +00:00
type: 'normal',
contexts: ['editable'],
documentUrlPatterns: [URLS.ownOrigin + 'edit*'],
click: (info, tab) => {
2018-10-06 05:02:45 +00:00
msg.sendTab(tab.id, {method: 'editDeleteText'});
},
}
};
2017-03-18 22:35:27 +00:00
2017-11-25 13:24:07 +00:00
if (chrome.contextMenus) {
const createContextMenus = ids => {
2017-04-29 16:54:16 +00:00
for (const id of ids) {
let item = contextMenus[id];
if (item.presentIf && !item.presentIf()) {
continue;
}
item = Object.assign({id}, item);
delete item.presentIf;
2017-04-29 16:54:16 +00:00
const prefValue = prefs.readOnlyValues[id];
item.title = chrome.i18n.getMessage(item.title);
2017-07-16 18:02:00 +00:00
if (!item.type && typeof prefValue === 'boolean') {
2017-04-29 16:54:16 +00:00
item.type = 'checkbox';
item.checked = prefValue;
}
if (!item.contexts) {
item.contexts = ['browser_action'];
}
delete item.click;
chrome.contextMenus.create(item, ignoreChromeError);
}
};
// circumvent the bug with disabling check marks in Chrome 62-64
const toggleCheckmark = CHROME >= 3172 && CHROME <= 3288 ?
(id => chrome.contextMenus.remove(id, () => createContextMenus([id]) + ignoreChromeError())) :
((id, checked) => chrome.contextMenus.update(id, {checked}, ignoreChromeError));
const togglePresence = (id, checked) => {
if (checked) {
createContextMenus([id]);
2017-04-29 16:54:16 +00:00
} else {
chrome.contextMenus.remove(id, ignoreChromeError);
2017-04-29 16:54:16 +00:00
}
};
const keys = Object.keys(contextMenus);
prefs.subscribe(keys.filter(id => typeof prefs.readOnlyValues[id] === 'boolean'), toggleCheckmark);
prefs.subscribe(keys.filter(id => contextMenus[id].presentIf), togglePresence);
createContextMenus(keys);
}
// *************************************************************************
// [re]inject content scripts
2017-09-03 18:25:19 +00:00
window.addEventListener('storageReady', function _() {
window.removeEventListener('storageReady', _);
2018-01-01 17:02:49 +00:00
updateIcon({
tab: {id: undefined},
styles: {},
});
2017-09-03 18:25:19 +00:00
// Firefox injects content script automatically
if (FIREFOX) return;
const NTP = 'chrome://newtab/';
const ALL_URLS = '<all_urls>';
const contentScripts = chrome.runtime.getManifest().content_scripts;
// expand * as .*?
const wildcardAsRegExp = (s, flags) => new RegExp(
s.replace(/[{}()[\]/\\.+?^$:=!|]/g, '\\$&')
.replace(/\*/g, '.*?'), flags);
for (const cs of contentScripts) {
cs.matches = cs.matches.map(m => (
2017-07-16 18:02:00 +00:00
m === ALL_URLS ? m : wildcardAsRegExp(m)
));
}
const injectCS = (cs, tabId) => {
ignoreChromeError();
2018-10-08 06:39:08 +00:00
for (const file of cs.js) {
chrome.tabs.executeScript(tabId, {
file,
runAt: cs.run_at,
allFrames: cs.all_frames,
matchAboutBlank: cs.match_about_blank,
}, ignoreChromeError);
}
};
const pingCS = (cs, {id, url}) => {
cs.matches.some(match => {
if ((match === ALL_URLS || url.match(match)) &&
(!url.startsWith('chrome') || url === NTP)) {
2018-10-08 07:30:39 +00:00
// TODO: add a `msg.pingTab` API?
2018-10-06 05:02:45 +00:00
msg.sendTab(id, {method: 'ping'})
2018-10-08 07:30:39 +00:00
.catch(() => false)
2018-10-06 05:02:45 +00:00
.then(pong => !pong && injectCS(cs, id));
return true;
}
});
};
queryTabs().then(tabs =>
tabs.forEach(tab => {
// skip lazy-loaded aka unloaded tabs that seem to start loading on message in FF
if (tab.width) {
contentScripts.forEach(cs =>
setTimeout(pingCS, 0, cs, tab));
}
}));
2017-09-03 18:25:19 +00:00
});
2018-10-07 13:20:39 +00:00
// FIXME: implement exposeIframes in apply.js
function webNavUsercssInstallerFF(data) {
const {tabId} = data;
Promise.all([
2018-10-08 07:30:39 +00:00
msg.sendTab(tabId, {method: 'ping'})
.catch(() => false),
// we need tab index to open the installer next to the original one
// and also to skip the double-invocation in FF which assigns tab url later
getTab(tabId),
]).then(([pong, tab]) => {
if (pong !== true && tab.url !== 'about:blank') {
2018-10-07 14:59:31 +00:00
window.API_METHODS.openUsercssInstallPage({direct: true}, {tab});
}
});
}
function webNavIframeHelperFF({tabId, frameId}) {
if (!frameId) return;
2018-10-06 05:02:45 +00:00
msg.sendTab(tabId, {method: 'ping'}, {frameId})
2018-10-08 07:30:39 +00:00
.catch(() => false)
2018-10-06 05:02:45 +00:00
.then(pong => {
if (pong) return;
2018-10-10 15:05:20 +00:00
// insert apply.js to iframe
const files = chrome.runtime.getManifest().content_scripts[0].js;
for (const file of files) {
chrome.tabs.executeScript(tabId, {
frameId,
file,
matchAboutBlank: true,
}, ignoreChromeError);
}
2018-10-06 05:02:45 +00:00
});
}
2018-01-01 17:02:49 +00:00
function updateIcon({tab, styles}) {
if (tab.id < 0) {
return;
}
if (URLS.chromeProtectsNTP && tab.url === 'chrome://newtab/') {
styles = {};
}
if (styles) {
2017-04-23 10:54:20 +00:00
stylesReceived(styles);
return;
}
2018-10-07 13:40:29 +00:00
styleManager.countStylesByUrl(tab.url, {enabled: true})
.then(count => stylesReceived({length: count}));
2018-07-22 14:15:09 +00:00
function stylesReceived(styles) {
2018-10-07 13:40:29 +00:00
const disableAll = prefs.get('disableAll');
const postfix = disableAll ? 'x' : !styles.length ? 'w' : '';
const color = prefs.get(disableAll ? 'badgeDisabled' : 'badgeNormal');
2018-10-07 13:40:29 +00:00
const text = prefs.get('show-badge') && styles.length ? String(styles.length) : '';
2017-06-28 10:49:04 +00:00
const iconset = ['', 'light/'][prefs.get('iconset')] || '';
let tabIcon = tabIcons.get(tab.id);
if (!tabIcon) tabIcons.set(tab.id, (tabIcon = {}));
2018-01-01 17:02:49 +00:00
if (tabIcon.iconType !== iconset + postfix) {
tabIcon.iconType = iconset + postfix;
const sizes = FIREFOX || CHROME >= 2883 && !VIVALDI ? [16, 32] : [19, 38];
const usePath = tabIcons.get('usePath');
Promise.all(sizes.map(size => {
const src = `/images/icon/${iconset}${size}${postfix}.png`;
return usePath ? src : tabIcons.get(src) || loadIcon(src);
})).then(data => {
const imageKey = typeof data[0] === 'string' ? 'path' : 'imageData';
const imageData = {};
sizes.forEach((size, i) => (imageData[size] = data[i]));
chrome.browserAction.setIcon({
tabId: tab.id,
[imageKey]: imageData,
}, ignoreChromeError);
});
2018-01-01 17:02:49 +00:00
}
if (tab.id === undefined) return;
2018-01-01 17:02:49 +00:00
let defaultIcon = tabIcons.get(undefined);
if (!defaultIcon) tabIcons.set(undefined, (defaultIcon = {}));
if (defaultIcon.color !== color) {
defaultIcon.color = color;
2017-04-23 10:54:20 +00:00
chrome.browserAction.setBadgeBackgroundColor({color});
2018-01-01 17:02:49 +00:00
}
if (tabIcon.text === text) return;
tabIcon.text = text;
try {
// Chrome supports the callback since 67.0.3381.0, see https://crbug.com/451320
chrome.browserAction.setBadgeText({text, tabId: tab.id}, ignoreChromeError);
} catch (e) {
setTimeout(() => {
getTab(tab.id).then(realTab => {
// skip pre-rendered tabs
if (realTab.index >= 0) {
chrome.browserAction.setBadgeText({text, tabId: tab.id});
}
});
2017-04-23 10:54:20 +00:00
});
2018-01-01 17:02:49 +00:00
}
}
function loadIcon(src, resolve) {
if (!resolve) return new Promise(resolve => loadIcon(src, resolve));
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = src;
img.onload = () => {
const w = canvas.width = img.width;
const h = canvas.height = img.height;
ctx.clearRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);
const data = ctx.getImageData(0, 0, w, h);
// Firefox breaks Canvas when privacy.resistFingerprinting=true, https://bugzil.la/1412961
let usePath = tabIcons.get('usePath');
if (usePath === undefined) {
usePath = data.data.every(b => b === 255);
tabIcons.set('usePath', usePath);
}
if (usePath) {
resolve(src);
return;
}
tabIcons.set(src, data);
resolve(data);
};
}
}
2018-10-06 05:02:45 +00:00
function onRuntimeMessage(msg, sender) {
2018-10-04 04:46:19 +00:00
if (msg.method !== 'invokeAPI') {
return;
}
2018-10-06 05:02:45 +00:00
const fn = window.API_METHODS[msg.name];
if (!fn) {
throw new Error(`unknown API: ${msg.name}`);
}
2018-10-06 05:02:45 +00:00
const context = {msg, sender};
return fn.apply(context, msg.args);
}