apply.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. // Not using some slow features of ES6, see http://kpdecker.github.io/six-speed/
  2. // like destructring, classes, defaults, spread, calculated key names
  3. /* eslint no-var: 0 */
  4. 'use strict';
  5. var ID_PREFIX = 'stylus-';
  6. var ROOT = document.documentElement;
  7. var isOwnPage = location.href.startsWith('chrome-extension:');
  8. var disableAll = false;
  9. var exposeIframes = false;
  10. var styleElements = new Map();
  11. var disabledElements = new Map();
  12. var retiredStyleTimers = new Map();
  13. var docRewriteObserver;
  14. requestStyles();
  15. chrome.runtime.onMessage.addListener(applyOnMessage);
  16. if (!isOwnPage) {
  17. window.dispatchEvent(new CustomEvent(chrome.runtime.id));
  18. window.addEventListener(chrome.runtime.id, orphanCheck, true);
  19. }
  20. function requestStyles(options, callback = applyStyles) {
  21. var matchUrl = location.href;
  22. if (!matchUrl.match(/^(http|file|chrome|ftp)/)) {
  23. // dynamic about: and javascript: iframes don't have an URL yet
  24. // so we'll try the parent frame which is guaranteed to have a real URL
  25. try {
  26. if (window != parent) {
  27. matchUrl = parent.location.href;
  28. }
  29. } catch (e) {}
  30. }
  31. const request = Object.assign({
  32. method: 'getStyles',
  33. matchUrl,
  34. enabled: true,
  35. asHash: true,
  36. }, options);
  37. // On own pages we request the styles directly to minimize delay and flicker
  38. if (typeof getStylesSafe !== 'undefined') {
  39. getStylesSafe(request).then(callback);
  40. } else {
  41. chrome.runtime.sendMessage(request, callback);
  42. }
  43. }
  44. function applyOnMessage(request, sender, sendResponse) {
  45. if (request.styles == 'DIY') {
  46. // Do-It-Yourself tells our built-in pages to fetch the styles directly
  47. // which is faster because IPC messaging JSON-ifies everything internally
  48. requestStyles({}, styles => {
  49. request.styles = styles;
  50. applyOnMessage(request);
  51. });
  52. return;
  53. }
  54. switch (request.method) {
  55. case 'styleDeleted':
  56. removeStyle(request);
  57. break;
  58. case 'styleUpdated':
  59. if (request.codeIsUpdated === false) {
  60. applyStyleState(request.style);
  61. break;
  62. }
  63. if (request.style.enabled) {
  64. removeStyle({id: request.style.id, retire: true});
  65. requestStyles({id: request.style.id});
  66. } else {
  67. removeStyle(request.style);
  68. }
  69. break;
  70. case 'styleAdded':
  71. if (request.style.enabled) {
  72. requestStyles({id: request.style.id});
  73. }
  74. break;
  75. case 'styleApply':
  76. applyStyles(request.styles);
  77. break;
  78. case 'styleReplaceAll':
  79. replaceAll(request.styles);
  80. break;
  81. case 'prefChanged':
  82. if ('disableAll' in request.prefs) {
  83. doDisableAll(request.prefs.disableAll);
  84. }
  85. if ('exposeIframes' in request.prefs) {
  86. doExposeIframes(request.prefs.exposeIframes);
  87. }
  88. break;
  89. case 'ping':
  90. sendResponse(true);
  91. break;
  92. }
  93. }
  94. function doDisableAll(disable = disableAll) {
  95. if (!disable === !disableAll) {
  96. return;
  97. }
  98. disableAll = disable;
  99. Array.prototype.forEach.call(document.styleSheets, stylesheet => {
  100. if (stylesheet.ownerNode.matches(`STYLE.stylus[id^="${ID_PREFIX}"]`)
  101. && stylesheet.disabled != disable) {
  102. stylesheet.disabled = disable;
  103. }
  104. });
  105. }
  106. function doExposeIframes(state = exposeIframes) {
  107. if (state === exposeIframes || window == parent) {
  108. return;
  109. }
  110. exposeIframes = state;
  111. const attr = document.documentElement.getAttribute('stylus-iframe');
  112. if (state && attr != '') {
  113. document.documentElement.setAttribute('stylus-iframe', '');
  114. } else if (!state && attr == '') {
  115. document.documentElement.removeAttribute('stylus-iframe');
  116. }
  117. }
  118. function applyStyleState({id, enabled}) {
  119. const inCache = disabledElements.get(id) || styleElements.get(id);
  120. const inDoc = document.getElementById(ID_PREFIX + id);
  121. if (enabled) {
  122. if (inDoc) {
  123. return;
  124. } else if (inCache) {
  125. addStyleElement(inCache);
  126. disabledElements.delete(id);
  127. } else {
  128. requestStyles({id});
  129. }
  130. } else {
  131. if (inDoc) {
  132. disabledElements.set(id, inDoc);
  133. inDoc.remove();
  134. }
  135. }
  136. }
  137. function removeStyle({id, retire = false}) {
  138. const el = document.getElementById(ID_PREFIX + id);
  139. if (el) {
  140. if (retire) {
  141. // to avoid page flicker when the style is updated
  142. // instead of removing it immediately we rename its ID and queue it
  143. // to be deleted in applyStyles after a new version is fetched and applied
  144. const deadID = 'ghost-' + id;
  145. el.id = ID_PREFIX + deadID;
  146. // in case something went wrong and new style was never applied
  147. retiredStyleTimers.set(deadID, setTimeout(removeStyle, 1000, {id: deadID}));
  148. } else {
  149. el.remove();
  150. }
  151. }
  152. styleElements.delete(ID_PREFIX + id);
  153. disabledElements.delete(id);
  154. retiredStyleTimers.delete(id);
  155. }
  156. function applyStyles(styles) {
  157. if (!styles) {
  158. // Chrome is starting up
  159. requestStyles();
  160. return;
  161. }
  162. if ('disableAll' in styles) {
  163. doDisableAll(styles.disableAll);
  164. delete styles.disableAll;
  165. }
  166. if ('exposeIframes' in styles) {
  167. doExposeIframes(styles.exposeIframes);
  168. delete styles.exposeIframes;
  169. }
  170. if (document.head
  171. && document.head.firstChild
  172. && document.head.firstChild.id == 'xml-viewer-style') {
  173. // when site response is application/xml Chrome displays our style elements
  174. // under document.documentElement as plain text so we need to move them into HEAD
  175. // which is already autogenerated at this moment
  176. ROOT = document.head;
  177. }
  178. for (const id in styles) {
  179. applySections(id, styles[id]);
  180. }
  181. initDocRewriteObserver();
  182. if (retiredStyleTimers.size) {
  183. setTimeout(() => {
  184. for (const [id, timer] of retiredStyleTimers.entries()) {
  185. removeStyle({id});
  186. clearTimeout(timer);
  187. }
  188. });
  189. }
  190. }
  191. function applySections(styleId, sections) {
  192. let el = document.getElementById(ID_PREFIX + styleId);
  193. if (el) {
  194. return;
  195. }
  196. if (document.documentElement instanceof SVGSVGElement) {
  197. // SVG document style
  198. el = document.createElementNS('http://www.w3.org/2000/svg', 'style');
  199. } else if (document instanceof XMLDocument) {
  200. // XML document style
  201. el = document.createElementNS('http://www.w3.org/1999/xhtml', 'style');
  202. } else {
  203. // HTML document style; also works on HTML-embedded SVG
  204. el = document.createElement('style');
  205. }
  206. Object.assign(el, {
  207. id: ID_PREFIX + styleId,
  208. className: 'stylus',
  209. type: 'text/css',
  210. textContent: sections.map(section => section.code).join('\n'),
  211. });
  212. addStyleElement(el);
  213. styleElements.set(el.id, el);
  214. disabledElements.delete(styleId);
  215. }
  216. function addStyleElement(el) {
  217. if (ROOT && !document.getElementById(el.id)) {
  218. ROOT.appendChild(el);
  219. el.disabled = disableAll;
  220. }
  221. }
  222. function replaceAll(newStyles) {
  223. const oldStyles = Array.prototype.slice.call(
  224. document.querySelectorAll(`STYLE.stylus[id^="${ID_PREFIX}"]`));
  225. oldStyles.forEach(el => (el.id += '-ghost'));
  226. styleElements.clear();
  227. disabledElements.clear();
  228. [...retiredStyleTimers.values()].forEach(clearTimeout);
  229. retiredStyleTimers.clear();
  230. applyStyles(newStyles);
  231. oldStyles.forEach(el => el.remove());
  232. }
  233. function initDocRewriteObserver() {
  234. if (isOwnPage || docRewriteObserver || !styleElements.size) {
  235. return;
  236. }
  237. // re-add styles if we detect documentElement being recreated
  238. const reinjectStyles = () => {
  239. if (!styleElements) {
  240. return orphanCheck && orphanCheck();
  241. }
  242. ROOT = document.documentElement;
  243. for (const el of styleElements.values()) {
  244. addStyleElement(document.importNode(el, true));
  245. }
  246. };
  247. // detect documentElement being rewritten from inside the script
  248. docRewriteObserver = new MutationObserver(mutations => {
  249. for (let m = mutations.length; --m >= 0;) {
  250. const added = mutations[m].addedNodes;
  251. for (let n = added.length; --n >= 0;) {
  252. if (added[n].localName == 'html') {
  253. reinjectStyles();
  254. return;
  255. }
  256. }
  257. }
  258. });
  259. docRewriteObserver.observe(document, {childList: true});
  260. // detect dynamic iframes rewritten after creation by the embedder i.e. externally
  261. setTimeout(() => {
  262. if (document.documentElement != ROOT) {
  263. reinjectStyles();
  264. }
  265. });
  266. }
  267. function orphanCheck() {
  268. const port = chrome.runtime.connect();
  269. if (port) {
  270. port.disconnect();
  271. return;
  272. }
  273. // we're orphaned due to an extension update
  274. // we can detach the mutation observer
  275. if (docRewriteObserver) {
  276. docRewriteObserver.disconnect();
  277. }
  278. // we can detach event listeners
  279. window.removeEventListener(chrome.runtime.id, orphanCheck, true);
  280. // we can't detach chrome.runtime.onMessage because it's no longer connected internally
  281. // we can destroy our globals in this context to free up memory
  282. [ // functions
  283. 'addStyleElement',
  284. 'applyOnMessage',
  285. 'applySections',
  286. 'applyStyles',
  287. 'applyStyleState',
  288. 'doDisableAll',
  289. 'initDocRewriteObserver',
  290. 'orphanCheck',
  291. 'removeStyle',
  292. 'replaceAll',
  293. 'requestStyles',
  294. // variables
  295. 'ROOT',
  296. 'disabledElements',
  297. 'retiredStyleTimers',
  298. 'styleElements',
  299. 'docRewriteObserver',
  300. ].forEach(fn => (window[fn] = null));
  301. }