stylus/background/background.js

346 lines
10 KiB
JavaScript
Raw Normal View History

Add: install styles from *.user.css file Fix: handle dup name+namespace Fix: eslint eqeqeq Fix: trim @name's spaces Add: check update for userstyle Add: build CSS variable Fix: only check dup when id is not provided Refactor: userStyle2json -> userstyle.json Add: style for input Add: config dialog Fix: preserve config during update Fix: onchange doesn't fire on keyboard enter event Fix: remove empty file Add: validator. Metas must stay in the same line Add: warn the user if installation failed Fix: add some delay before starting installation Add: open the editor after first installation Fix: add openEditor to globals Fix: i18n Add: preprocessor. Move userstyle.build to background page. Fix: remove unused global Fix: preserved unknown prop in saveStyleSource() like saveStyle() Add: edit userstyle source Fix: load preprocessor dynamically Fix: load content script dynamically Fix: buildCode is async function Fix: drop Object.entries Fix: style.sections is undefined Fix: don't hide the name input but disable it Fix: query the style before installation Revert: changes to editor, editor.html Refactor: use term `usercss` instead of `userstyle` Fix: don't show homepage action for usercss Refactor: move script-loader to js/ Refactor: pull out mozParser Fix: code style Fix: we don't need to build meta anymore Fix: use saveUsercss instead of saveStyle to get responsed error Fix: last is undefined, load script error Fix: switch to moz-format Fix: drop injectContentScript. Move usercss check into install-user-css Fix: response -> respond Fix: globals -> global Fix: queryUsercss -> filterUsercss Fix: add processUsercss function Fix: only open editor for usercss Fix: remove findupUsercss fixme Fix: globals -> global Fix: globals -> global Fix: global pollution Revert: update.js Refactor: checkStyle Add: support usercss Fix: no need to getURL in background page Fix: merget semver.js into usercss.js Fix: drop all_urls in match pattern Fix: drop respondWithError Move stylus -> stylus-lang Add stylus-lang/readme Fix: use include_globs Fix: global pollution
2017-08-05 16:49:25 +00:00
/* global dbExec, getStyles, saveStyle, filterUsercss, saveUsercss */
'use strict';
// eslint-disable-next-line no-var
var browserCommands, contextMenus;
// *************************************************************************
// preload the DB
tryCatch(getStyles);
// *************************************************************************
// register all listeners
chrome.runtime.onMessage.addListener(onRuntimeMessage);
{
const listener =
URLS.chromeProtectsNTP
? webNavigationListenerChrome
: webNavigationListener;
chrome.webNavigation.onBeforeNavigate.addListener(data =>
listener(null, data));
chrome.webNavigation.onCommitted.addListener(data =>
listener('styleApply', data));
chrome.webNavigation.onHistoryStateUpdated.addListener(data =>
listener('styleReplaceAll', data));
chrome.webNavigation.onReferenceFragmentUpdated.addListener(data =>
listener('styleReplaceAll', data));
}
chrome.contextMenus.onClicked.addListener((info, tab) =>
contextMenus[info.menuItemId].click(info, tab));
if ('commands' in chrome) {
// Not available in Firefox - https://bugzilla.mozilla.org/show_bug.cgi?id=1240350
chrome.commands.onCommand.addListener(command => browserCommands[command]());
}
// *************************************************************************
// set the default icon displayed after a tab is created until webNavigation kicks in
prefs.subscribe(() => updateIcon({id: undefined}, {}), ['iconset']);
updateIcon({id: undefined}, {});
// *************************************************************************
2017-04-24 13:26:59 +00:00
{
const onInstall = ({reason}) => {
chrome.runtime.onInstalled.removeListener(onInstall);
const manifest = chrome.runtime.getManifest();
// Open FAQs page once after installation to guide new users.
// Do not display it in development mode.
2017-07-16 18:02:00 +00:00
if (reason === 'install' && manifest.update_url) {
setTimeout(openURL, 100, {
url: 'http://add0n.com/stylus.html'
2017-04-24 13:26:59 +00:00
});
}
// reset L10N cache on update
2017-07-16 18:02:00 +00:00
if (reason === 'update') {
2017-04-24 13:26:59 +00:00
localStorage.L10N = JSON.stringify({
browserUIlanguage: chrome.i18n.getUILanguage(),
});
}
// TODO: remove in the future
// embed style digests
chrome.storage.local.get(null, data => {
const digestKeys = Object.keys(data).filter(key => key.startsWith('originalDigest'));
if (!digestKeys.length) {
return;
}
chrome.storage.local.remove(digestKeys);
getStyles().then(styles => {
for (const style of styles) {
const digest = data['originalDigest' + style.id];
if (!style.originalDigest && digest) {
style.originalDigest = digest;
dbExec('put', style);
}
}
});
});
};
// bind for 60 seconds max and auto-unbind if it's a normal run
2017-04-24 13:26:59 +00:00
chrome.runtime.onInstalled.addListener(onInstall);
setTimeout(onInstall, 60e3, {reason: 'unbindme'});
2017-03-18 22:35:27 +00:00
}
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 = Object.assign({
'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,
},
}, !FIREFOX && prefs.get('editor.contextDelete') && {
2017-04-29 16:54:16 +00:00
'editor.contextDelete': {
title: 'editDeleteText',
2017-04-29 16:54:16 +00:00
type: 'normal',
contexts: ['editable'],
documentUrlPatterns: [URLS.ownOrigin + 'edit*'],
click: (info, tab) => {
chrome.tabs.sendMessage(tab.id, {method: 'editDeleteText'});
},
}
});
2017-03-18 22:35:27 +00:00
2017-04-29 16:54:16 +00:00
{
const createContextMenus = (ids = Object.keys(contextMenus)) => {
for (const id of ids) {
const item = Object.assign({id}, contextMenus[id]);
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);
}
};
createContextMenus();
prefs.subscribe((id, checked) => {
2017-07-16 18:02:00 +00:00
if (id === 'editor.contextDelete') {
2017-04-29 16:54:16 +00:00
if (checked) {
createContextMenus([id]);
} else {
chrome.contextMenus.remove(id, ignoreChromeError);
}
} else {
chrome.contextMenus.update(id, {checked}, ignoreChromeError);
}
2017-07-16 18:02:00 +00:00
}, Object.keys(contextMenus).filter(key => typeof prefs.readOnlyValues[key] === 'boolean'));
}
// *************************************************************************
// [re]inject content scripts
{
const NTP = 'chrome://newtab/';
const PING = {method: 'ping'};
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) => {
chrome.tabs.executeScript(tabId, {
file: cs.js[0],
runAt: cs.run_at,
allFrames: cs.all_frames,
matchAboutBlank: cs.match_about_blank,
}, ignoreChromeError);
};
const pingCS = (cs, {id, url}) => {
cs.matches.some(match => {
2017-07-16 18:02:00 +00:00
if ((match === ALL_URLS || url.match(match))
&& (!url.startsWith('chrome') || url === NTP)) {
chrome.tabs.sendMessage(id, PING, pong => {
if (!pong) {
injectCS(cs, id);
}
ignoreChromeError();
});
return true;
}
});
};
queryTabs().then(tabs =>
tabs.forEach(tab => {
// skip lazy-loaded aka unloaded tabs that seem to start loading on message in FF
if (!FIREFOX || tab.width) {
contentScripts.forEach(cs =>
setTimeout(pingCS, 0, cs, tab));
}
}));
}
// *************************************************************************
function webNavigationListener(method, {url, tabId, frameId}) {
2017-04-25 21:48:27 +00:00
getStyles({matchUrl: url, enabled: true, asHash: true}).then(styles => {
if (method && !url.startsWith('chrome:') && tabId >= 0) {
chrome.tabs.sendMessage(tabId, {
method,
// ping own page so it retrieves the styles directly
styles: url.startsWith(URLS.ownOrigin) ? 'DIY' : styles,
}, {
frameId
}, ignoreChromeError);
}
// main page frame id is 0
2017-07-16 18:02:00 +00:00
if (frameId === 0) {
updateIcon({id: tabId, url}, styles);
}
});
}
function webNavigationListenerChrome(method, data) {
// Chrome 61.0.3161+ doesn't run content scripts on NTP
if (
!data.url.startsWith('https://www.google.') ||
!data.url.includes('/_/chrome/newtab?')
) {
webNavigationListener(method, data);
return;
}
getTab(data.tabId).then(tab => {
if (tab.url === 'chrome://newtab/') {
data.url = tab.url;
}
webNavigationListener(method, data);
});
}
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;
}
2017-04-25 21:48:27 +00:00
getTabRealURL(tab)
.then(url => getStyles({matchUrl: url, enabled: true, asHash: true}))
.then(stylesReceived);
function stylesReceived(styles) {
let numStyles = styles.length;
if (numStyles === undefined) {
// for 'styles' asHash:true fake the length by counting numeric ids manually
numStyles = 0;
for (const id of Object.keys(styles)) {
numStyles += id.match(/^\d+$/) ? 1 : 0;
}
}
const disableAll = 'disableAll' in styles ? styles.disableAll : prefs.get('disableAll');
2017-07-16 18:02:00 +00:00
const postfix = disableAll ? 'x' : numStyles === 0 ? 'w' : '';
const color = prefs.get(disableAll ? 'badgeDisabled' : 'badgeNormal');
const text = prefs.get('show-badge') && numStyles ? String(numStyles) : '';
2017-06-28 10:49:04 +00:00
const iconset = ['', 'light/'][prefs.get('iconset')] || '';
const path = 'images/icon/' + iconset;
chrome.browserAction.setIcon({
tabId: tab.id,
path: {
// Material Design 2016 new size is 16px
2017-06-28 10:49:04 +00:00
16: `${path}16${postfix}.png`,
32: `${path}32${postfix}.png`,
// Chromium forks or non-chromium browsers may still use the traditional 19px
2017-06-28 10:49:04 +00:00
19: `${path}19${postfix}.png`,
38: `${path}38${postfix}.png`,
// TODO: add Edge preferred sizes: 20, 25, 30, 40
},
}, () => {
if (chrome.runtime.lastError || tab.id === undefined) {
2017-04-23 10:54:20 +00:00
return;
}
2017-04-23 10:54:20 +00:00
// Vivaldi bug workaround: setBadgeText must follow setBadgeBackgroundColor
chrome.browserAction.setBadgeBackgroundColor({color});
getTab(tab.id).then(realTab => {
2017-07-22 04:39:43 +00:00
// skip pre-rendered tabs
if (realTab.index >= 0) {
2017-07-22 04:39:43 +00:00
chrome.browserAction.setBadgeText({text, tabId: tab.id});
}
2017-04-23 10:54:20 +00:00
});
});
}
}
function onRuntimeMessage(request, sender, sendResponse) {
// prevent browser exception bug on sending a response to a closed tab
sendResponse = (sendResponseOriginal =>
data => {
try {
sendResponseOriginal(data);
} catch (e) {}
}
)(sendResponse);
switch (request.method) {
case 'getStyles':
2017-04-25 21:48:27 +00:00
getStyles(request).then(sendResponse);
return KEEP_CHANNEL_OPEN;
case 'saveStyle':
saveStyle(request).then(sendResponse);
return KEEP_CHANNEL_OPEN;
Add: install styles from *.user.css file Fix: handle dup name+namespace Fix: eslint eqeqeq Fix: trim @name's spaces Add: check update for userstyle Add: build CSS variable Fix: only check dup when id is not provided Refactor: userStyle2json -> userstyle.json Add: style for input Add: config dialog Fix: preserve config during update Fix: onchange doesn't fire on keyboard enter event Fix: remove empty file Add: validator. Metas must stay in the same line Add: warn the user if installation failed Fix: add some delay before starting installation Add: open the editor after first installation Fix: add openEditor to globals Fix: i18n Add: preprocessor. Move userstyle.build to background page. Fix: remove unused global Fix: preserved unknown prop in saveStyleSource() like saveStyle() Add: edit userstyle source Fix: load preprocessor dynamically Fix: load content script dynamically Fix: buildCode is async function Fix: drop Object.entries Fix: style.sections is undefined Fix: don't hide the name input but disable it Fix: query the style before installation Revert: changes to editor, editor.html Refactor: use term `usercss` instead of `userstyle` Fix: don't show homepage action for usercss Refactor: move script-loader to js/ Refactor: pull out mozParser Fix: code style Fix: we don't need to build meta anymore Fix: use saveUsercss instead of saveStyle to get responsed error Fix: last is undefined, load script error Fix: switch to moz-format Fix: drop injectContentScript. Move usercss check into install-user-css Fix: response -> respond Fix: globals -> global Fix: queryUsercss -> filterUsercss Fix: add processUsercss function Fix: only open editor for usercss Fix: remove findupUsercss fixme Fix: globals -> global Fix: globals -> global Fix: global pollution Revert: update.js Refactor: checkStyle Add: support usercss Fix: no need to getURL in background page Fix: merget semver.js into usercss.js Fix: drop all_urls in match pattern Fix: drop respondWithError Move stylus -> stylus-lang Add stylus-lang/readme Fix: use include_globs Fix: global pollution
2017-08-05 16:49:25 +00:00
case 'saveUsercss':
saveUsercss(request).then(sendResponse);
return KEEP_CHANNEL_OPEN;
case 'filterUsercss':
filterUsercss(request).then(sendResponse);
return KEEP_CHANNEL_OPEN;
case 'healthCheck':
2017-04-25 21:48:27 +00:00
dbExec()
.then(() => sendResponse(true))
.catch(() => sendResponse(false));
return KEEP_CHANNEL_OPEN;
case 'download':
download(request.url)
.then(sendResponse)
.catch(() => sendResponse(null));
return KEEP_CHANNEL_OPEN;
}
}