style-via-api.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /* global getStyles */
  2. 'use strict';
  3. // eslint-disable-next-line no-var
  4. var styleViaAPI = !CHROME && (() => {
  5. const ACTIONS = {
  6. styleApply,
  7. styleDeleted,
  8. styleUpdated,
  9. styleAdded,
  10. styleReplaceAll,
  11. prefChanged,
  12. ping,
  13. };
  14. const NOP = Promise.resolve(new Error('NOP'));
  15. const PONG = Promise.resolve(true);
  16. const onError = () => {};
  17. /* <tabId>: Object
  18. <frameId>: Object
  19. url: String, non-enumerable
  20. <styleId>: Array of strings
  21. section code */
  22. const cache = new Map();
  23. const allFrameUrls = new Map();
  24. let observingTabs = false;
  25. return {
  26. process,
  27. getFrameUrl,
  28. setFrameUrl,
  29. allFrameUrls,
  30. cache,
  31. };
  32. function process(request, sender) {
  33. const action = ACTIONS[request.action || request.method];
  34. if (!action) {
  35. return NOP;
  36. }
  37. const {frameId, tab: {id: tabId}} = sender;
  38. if (isNaN(frameId)) {
  39. const frameIds = Object.keys(allFrameUrls.get(tabId) || {});
  40. if (frameIds.length > 1) {
  41. return Promise.all(
  42. frameIds.map(frameId =>
  43. process(request, Object.assign({}, sender, {frameId: Number(frameId)}))));
  44. }
  45. sender.frameId = 0;
  46. }
  47. return action(request, sender)
  48. .catch(onError)
  49. .then(maybeToggleObserver);
  50. }
  51. function styleApply({
  52. id = null,
  53. ignoreUrlCheck,
  54. }, {
  55. tab,
  56. frameId,
  57. url = getFrameUrl(tab.id, frameId),
  58. }) {
  59. if (prefs.get('disableAll')) {
  60. return NOP;
  61. }
  62. const {tabFrames, frameStyles} = getCachedData(tab.id, frameId);
  63. if (id === null && !ignoreUrlCheck && frameStyles.url === url) {
  64. return NOP;
  65. }
  66. return getStyles({id, matchUrl: url, enabled: true, asHash: true}).then(styles => {
  67. const tasks = [];
  68. for (const styleId in styles) {
  69. if (isNaN(parseInt(styleId))) {
  70. continue;
  71. }
  72. // shallow-extract code from the sections array in order to reuse references
  73. // in other places whereas the combined string gets garbage-collected
  74. const styleSections = styles[styleId].map(section => section.code);
  75. const code = styleSections.join('\n');
  76. if (!code) {
  77. delete frameStyles[styleId];
  78. continue;
  79. }
  80. if (code === (frameStyles[styleId] || []).join('\n')) {
  81. continue;
  82. }
  83. frameStyles[styleId] = styleSections;
  84. tasks.push(
  85. browser.tabs.insertCSS(tab.id, {
  86. code,
  87. frameId,
  88. runAt: 'document_start',
  89. matchAboutBlank: true,
  90. }).catch(onError));
  91. }
  92. Object.defineProperty(frameStyles, 'url', {value: url, configurable: true});
  93. tabFrames[frameId] = frameStyles;
  94. cache.set(tab.id, tabFrames);
  95. return Promise.all(tasks);
  96. });
  97. }
  98. function styleDeleted({id}, {tab, frameId}) {
  99. const {frameStyles, styleSections} = getCachedData(tab.id, frameId, id);
  100. const code = styleSections.join('\n');
  101. if (code && !duplicateCodeExists({frameStyles, id, code})) {
  102. return removeCSS(tab.id, frameId, code).then(() => {
  103. delete frameStyles[id];
  104. });
  105. } else {
  106. return NOP;
  107. }
  108. }
  109. function styleUpdated({style}, sender) {
  110. if (!style.enabled) {
  111. return styleDeleted(style, sender);
  112. }
  113. const {tab, frameId} = sender;
  114. const {frameStyles, styleSections} = getCachedData(tab.id, frameId, style.id);
  115. const code = styleSections.join('\n');
  116. return styleApply(style, sender).then(code && (() => {
  117. if (!duplicateCodeExists({frameStyles, code, id: null})) {
  118. return removeCSS(tab.id, frameId, code);
  119. }
  120. }));
  121. }
  122. function styleAdded({style}, sender) {
  123. return style.enabled ? styleApply(style, sender) : NOP;
  124. }
  125. function styleReplaceAll(request, sender) {
  126. const {tab, frameId} = sender;
  127. const oldStylesCode = getFrameStylesJoined(sender);
  128. return styleApply({ignoreUrlCheck: true}, sender).then(() => {
  129. const newStylesCode = getFrameStylesJoined(sender);
  130. const tasks = oldStylesCode
  131. .filter(code => !newStylesCode.includes(code))
  132. .map(code => removeCSS(tab.id, frameId, code));
  133. return Promise.all(tasks);
  134. });
  135. }
  136. function prefChanged({prefs}, sender) {
  137. if ('disableAll' in prefs) {
  138. if (!prefs.disableAll) {
  139. return styleApply({}, sender);
  140. }
  141. const {tab, frameId} = sender;
  142. const {tabFrames, frameStyles} = getCachedData(tab.id, frameId);
  143. if (isEmpty(frameStyles)) {
  144. return NOP;
  145. }
  146. delete tabFrames[frameId];
  147. const tasks = Object.keys(frameStyles)
  148. .map(id => removeCSS(tab.id, frameId, frameStyles[id].join('\n')));
  149. return Promise.all(tasks);
  150. } else {
  151. return NOP;
  152. }
  153. }
  154. function ping() {
  155. return PONG;
  156. }
  157. /* utilities */
  158. function maybeToggleObserver(passthru) {
  159. let method;
  160. if (!observingTabs && cache.size) {
  161. method = 'addListener';
  162. } else if (observingTabs && !cache.size) {
  163. method = 'removeListener';
  164. } else {
  165. return passthru;
  166. }
  167. observingTabs = !observingTabs;
  168. chrome.webNavigation.onCommitted[method](onNavigationCommitted);
  169. chrome.tabs.onRemoved[method](onTabRemoved);
  170. chrome.tabs.onReplaced[method](onTabReplaced);
  171. return passthru;
  172. }
  173. function onNavigationCommitted({tabId, frameId}) {
  174. if (frameId === 0) {
  175. onTabRemoved(tabId);
  176. return;
  177. }
  178. const tabFrames = cache.get(tabId);
  179. if (tabFrames && frameId in tabFrames) {
  180. delete tabFrames[frameId];
  181. if (isEmpty(tabFrames)) {
  182. onTabRemoved(tabId);
  183. }
  184. }
  185. }
  186. function onTabRemoved(tabId) {
  187. cache.delete(tabId);
  188. maybeToggleObserver();
  189. }
  190. function onTabReplaced(addedTabId, removedTabId) {
  191. onTabRemoved(removedTabId);
  192. }
  193. function getCachedData(tabId, frameId, styleId) {
  194. const tabFrames = cache.get(tabId) || {};
  195. const frameStyles = tabFrames[frameId] || {};
  196. const styleSections = styleId && frameStyles[styleId] || [];
  197. return {tabFrames, frameStyles, styleSections};
  198. }
  199. function getFrameUrl(tabId, frameId = 0) {
  200. const frameUrls = allFrameUrls.get(tabId);
  201. return frameUrls && frameUrls[frameId] || '';
  202. }
  203. function setFrameUrl(tabId, frameId, url) {
  204. const frameUrls = allFrameUrls.get(tabId);
  205. if (frameUrls) {
  206. frameUrls[frameId] = url;
  207. } else {
  208. allFrameUrls.set(tabId, {[frameId]: url});
  209. }
  210. }
  211. function getFrameStylesJoined({
  212. tab,
  213. frameId,
  214. frameStyles = getCachedData(tab.id, frameId).frameStyles,
  215. }) {
  216. return Object.keys(frameStyles).map(id => frameStyles[id].join('\n'));
  217. }
  218. function duplicateCodeExists({
  219. tab,
  220. frameId,
  221. frameStyles = getCachedData(tab.id, frameId).frameStyles,
  222. frameStylesCode = {},
  223. id,
  224. code = frameStylesCode[id] || frameStyles[id].join('\n'),
  225. }) {
  226. id = String(id);
  227. for (const styleId in frameStyles) {
  228. if (id !== styleId &&
  229. code === (frameStylesCode[styleId] || frameStyles[styleId].join('\n'))) {
  230. return true;
  231. }
  232. }
  233. }
  234. function removeCSS(tabId, frameId, code) {
  235. return browser.tabs.removeCSS(tabId, {frameId, code, matchAboutBlank: true})
  236. .catch(onError);
  237. }
  238. function isEmpty(obj) {
  239. for (const k in obj) {
  240. return false;
  241. }
  242. return true;
  243. }
  244. })();