stylus/background/content-scripts.js
narcolepticinsomniac 1f12d50aaf
Embed options in manager (#828)
* Embed options in manager

* fix indent again

* Fix edit URL detected as manage URL when creating manager style from popup

* Syntax, hash only, and prevent empty hash

* Fix: move origin check to background

* Rename eslintrc

* Refactor: openURL

* Add: fixme comment about openEditor

* Fix: allow activating manager in other windows

* Add: trimHash method

* Fix: limit the scope of styleViaAPI

* Breaking: add router, keep search params

* Fix: focus options when activated

* Add: some fixme

* Fix: remove unused fixme

* Fix: minor

* Fix: remove unused message

* Add: doc

* Change: activate manager in other windows

* Fix: make sure sender is available in getTabUrlPrefix

* Add: openManage API

* Change: reuse editor in openEditor

* Fix: greedly pop the buffer

* Fix: backward detection

* Fix: remove unused important

* Fix: remove unused workaround

* Fix: avoid empty search param

* Change: detect all kinds of manager in openManage

* Fix: minor

* Manage button text

Co-authored-by: eight <eight04@gmail.com>
2020-02-01 23:36:54 -05:00

69 lines
1.9 KiB
JavaScript

/* global msg queryTabs ignoreChromeError */
/* exported contentScripts */
'use strict';
const contentScripts = (() => {
const NTP = 'chrome://newtab/';
const ALL_URLS = '<all_urls>';
const SCRIPTS = chrome.runtime.getManifest().content_scripts;
// expand * as .*?
const wildcardAsRegExp = (s, flags) => new RegExp(
s.replace(/[{}()[\]/\\.+?^$:=!|]/g, '\\$&')
.replace(/\*/g, '.*?'), flags);
for (const cs of SCRIPTS) {
cs.matches = cs.matches.map(m => (
m === ALL_URLS ? m : wildcardAsRegExp(m)
));
}
return {injectToTab, injectToAllTabs};
function injectToTab({url, tabId, frameId = null}) {
for (const script of SCRIPTS) {
if (
script.matches.some(match =>
(match === ALL_URLS || url.match(match)) &&
(!url.startsWith('chrome') || url === NTP))
) {
doInject(tabId, frameId, script);
}
}
}
function doInject(tabId, frameId, script) {
const options = frameId === null ? {} : {frameId};
msg.sendTab(tabId, {method: 'ping'}, options)
.catch(() => false)
.then(pong => {
if (pong) {
return;
}
const options = {
runAt: script.run_at,
allFrames: script.all_frames,
matchAboutBlank: script.match_about_blank
};
if (frameId !== null) {
options.allFrames = false;
options.frameId = frameId;
}
for (const file of script.js) {
chrome.tabs.executeScript(tabId, Object.assign({file}, options), ignoreChromeError);
}
});
}
function injectToAllTabs() {
return queryTabs({}).then(tabs => {
for (const tab of tabs) {
// skip lazy-loaded aka unloaded tabs that seem to start loading on message in FF
if (tab.width) {
injectToTab({
url: tab.url,
tabId: tab.id
});
}
}
});
}
})();