single-file-helper.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global CustomEvent, addEventListener, dispatchEvent */
  24. this.singlefile.lib.helper = this.singlefile.lib.helper || (() => {
  25. const singlefile = this.singlefile;
  26. const ON_BEFORE_CAPTURE_EVENT_NAME = "single-file-on-before-capture";
  27. const ON_AFTER_CAPTURE_EVENT_NAME = "single-file-on-after-capture";
  28. const REMOVED_CONTENT_ATTRIBUTE_NAME = "data-single-file-removed-content";
  29. const HIDDEN_CONTENT_ATTRIBUTE_NAME = "data-single-file-hidden-content";
  30. const PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME = "data-single-file-preserved-space-element";
  31. const SHADOW_ROOT_ATTRIBUTE_NAME = "data-single-file-shadow-root-element";
  32. const WIN_ID_ATTRIBUTE_NAME = "data-single-file-win-id";
  33. const IMAGE_ATTRIBUTE_NAME = "data-single-file-image";
  34. const POSTER_ATTRIBUTE_NAME = "data-single-file-poster";
  35. const CANVAS_ATTRIBUTE_NAME = "data-single-file-canvas";
  36. const HTML_IMPORT_ATTRIBUTE_NAME = "data-single-file-import";
  37. const INPUT_VALUE_ATTRIBUTE_NAME = "data-single-file-input-value";
  38. const LAZY_SRC_ATTRIBUTE_NAME = "data-single-file-lazy-loaded-src";
  39. const STYLESHEET_ATTRIBUTE_NAME = "data-single-file-stylesheet";
  40. const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-single-file-disabled-noscript";
  41. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  42. const IGNORED_REMOVED_TAG_NAMES = ["NOSCRIPT", "DISABLED-NOSCRIPT", "META", "LINK", "STYLE", "TITLE", "TEMPLATE", "SOURCE", "OBJECT", "SCRIPT", "HEAD"];
  43. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  44. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  45. const FONT_WEIGHTS = {
  46. normal: "400",
  47. bold: "700"
  48. };
  49. addEventListener("single-file-user-script-init", () => singlefile.lib.helper.waitForUserScript = async eventPrefixName => {
  50. const event = new CustomEvent(eventPrefixName + "-request", { cancelable: true });
  51. const promiseResponse = new Promise(resolve => addEventListener(eventPrefixName + "-response", resolve));
  52. dispatchEvent(event);
  53. if (event.defaultPrevented) {
  54. await promiseResponse;
  55. }
  56. });
  57. return {
  58. initDoc,
  59. preProcessDoc,
  60. postProcessDoc,
  61. serialize,
  62. removeQuotes,
  63. ON_BEFORE_CAPTURE_EVENT_NAME,
  64. ON_AFTER_CAPTURE_EVENT_NAME,
  65. WIN_ID_ATTRIBUTE_NAME,
  66. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  67. REMOVED_CONTENT_ATTRIBUTE_NAME,
  68. HIDDEN_CONTENT_ATTRIBUTE_NAME,
  69. IMAGE_ATTRIBUTE_NAME,
  70. POSTER_ATTRIBUTE_NAME,
  71. CANVAS_ATTRIBUTE_NAME,
  72. INPUT_VALUE_ATTRIBUTE_NAME,
  73. SHADOW_ROOT_ATTRIBUTE_NAME,
  74. HTML_IMPORT_ATTRIBUTE_NAME,
  75. LAZY_SRC_ATTRIBUTE_NAME,
  76. STYLESHEET_ATTRIBUTE_NAME,
  77. SELECTED_CONTENT_ATTRIBUTE_NAME
  78. };
  79. function initDoc(doc) {
  80. doc.querySelectorAll("meta[http-equiv=refresh]").forEach(element => {
  81. element.removeAttribute("http-equiv");
  82. element.setAttribute("disabled-http-equiv", "refresh");
  83. });
  84. }
  85. function preProcessDoc(doc, win, options) {
  86. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  87. doc.querySelectorAll("noscript").forEach(element => {
  88. const disabledNoscriptElement = doc.createElement("template");
  89. disabledNoscriptElement.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, "");
  90. disabledNoscriptElement.textContent = element.textContent;
  91. element.parentElement.replaceChild(disabledNoscriptElement, element);
  92. });
  93. initDoc(doc);
  94. if (doc.head) {
  95. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  96. }
  97. let elementsInfo;
  98. if (win && doc.documentElement) {
  99. elementsInfo = getElementsInfo(win, doc, doc.documentElement, options);
  100. } else {
  101. elementsInfo = {
  102. canvases: [],
  103. images: [],
  104. posters: [],
  105. usedFonts: [],
  106. shadowRoots: [],
  107. imports: [],
  108. markedElements: []
  109. };
  110. }
  111. return {
  112. canvases: elementsInfo.canvases,
  113. fonts: getFontsData(doc),
  114. stylesheets: getStylesheetsData(doc),
  115. images: elementsInfo.images,
  116. posters: elementsInfo.posters,
  117. usedFonts: Array.from(elementsInfo.usedFonts.values()),
  118. shadowRoots: elementsInfo.shadowRoots,
  119. imports: elementsInfo.imports,
  120. referrer: doc.referrer,
  121. markedElements: elementsInfo.markedElements
  122. };
  123. }
  124. function getElementsInfo(win, doc, element, options, data = { usedFonts: new Map(), canvases: [], images: [], posters: [], shadowRoots: [], imports: [], markedElements: [] }, ascendantHidden) {
  125. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  126. elements.forEach(element => {
  127. let elementHidden, computedStyle;
  128. if (options.removeHiddenElements || options.removeUnusedFonts || options.compressHTML) {
  129. computedStyle = win.getComputedStyle(element);
  130. if (options.removeHiddenElements) {
  131. if (ascendantHidden) {
  132. Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement).forEach(element => {
  133. if (!IGNORED_REMOVED_TAG_NAMES.includes(element.tagName)) {
  134. element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
  135. data.markedElements.push(element);
  136. }
  137. });
  138. }
  139. elementHidden = ascendantHidden || testHiddenElement(element, computedStyle, data.markedElements);
  140. }
  141. if (!elementHidden) {
  142. if (options.compressHTML && computedStyle) {
  143. const whiteSpace = computedStyle.getPropertyValue("white-space");
  144. if (whiteSpace && whiteSpace.startsWith("pre")) {
  145. element.setAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, "");
  146. data.markedElements.push(element);
  147. }
  148. }
  149. if (options.removeUnusedFonts) {
  150. getUsedFont(computedStyle, options, data.usedFonts);
  151. getUsedFont(win.getComputedStyle(element, ":first-letter"), options, data.usedFonts);
  152. getUsedFont(win.getComputedStyle(element, ":before"), options, data.usedFonts);
  153. getUsedFont(win.getComputedStyle(element, ":after"), options, data.usedFonts);
  154. }
  155. }
  156. }
  157. getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle);
  158. if (element.shadowRoot) {
  159. const shadowRootInfo = {};
  160. element.setAttribute(SHADOW_ROOT_ATTRIBUTE_NAME, data.shadowRoots.length);
  161. data.markedElements.push(element);
  162. data.shadowRoots.push(shadowRootInfo);
  163. getElementsInfo(win, doc, element.shadowRoot, options, data, elementHidden);
  164. shadowRootInfo.content = element.shadowRoot.innerHTML;
  165. shadowRootInfo.delegatesFocus = element.shadowRoot.delegatesFocus;
  166. shadowRootInfo.mode = element.shadowRoot.mode;
  167. if (element.shadowRoot.adoptedStyleSheets && element.shadowRoot.adoptedStyleSheets.length) {
  168. shadowRootInfo.adoptedStyleSheets = Array.from(element.shadowRoot.adoptedStyleSheets).map(stylesheet => Array.from(stylesheet.cssRules).map(cssRule => cssRule.cssText).join("\n"));
  169. }
  170. }
  171. getElementsInfo(win, doc, element, options, data, elementHidden);
  172. });
  173. return data;
  174. }
  175. function getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle) {
  176. if (element.tagName == "CANVAS") {
  177. try {
  178. const size = getSize(win, element, computedStyle);
  179. data.canvases.push({ dataURI: element.toDataURL("image/png", ""), width: size.width, height: size.height });
  180. element.setAttribute(CANVAS_ATTRIBUTE_NAME, data.canvases.length - 1);
  181. data.markedElements.push(element);
  182. } catch (error) {
  183. // ignored
  184. }
  185. }
  186. if (element.tagName == "IMG") {
  187. const imageData = {
  188. currentSrc: elementHidden ?
  189. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" :
  190. (options.loadDeferredImages && element.getAttribute(LAZY_SRC_ATTRIBUTE_NAME)) || element.currentSrc
  191. };
  192. data.images.push(imageData);
  193. element.setAttribute(IMAGE_ATTRIBUTE_NAME, data.images.length - 1);
  194. data.markedElements.push(element);
  195. element.removeAttribute(LAZY_SRC_ATTRIBUTE_NAME);
  196. computedStyle = computedStyle || win.getComputedStyle(element);
  197. if (computedStyle) {
  198. imageData.size = getSize(win, element, computedStyle);
  199. const boxShadow = computedStyle.getPropertyValue("box-shadow");
  200. const backgroundImage = computedStyle.getPropertyValue("background-image");
  201. if ((!boxShadow || boxShadow == "none") &&
  202. (!backgroundImage || backgroundImage == "none") &&
  203. (imageData.size.pxWidth > 1 || imageData.size.pxHeight > 1)) {
  204. imageData.replaceable = true;
  205. imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
  206. imageData.objectFit = computedStyle.getPropertyValue("object-fit");
  207. imageData.boxSizing = computedStyle.getPropertyValue("box-sizing");
  208. imageData.objectPosition = computedStyle.getPropertyValue("object-position");
  209. }
  210. }
  211. }
  212. if (element.tagName == "VIDEO") {
  213. if (!element.poster) {
  214. const canvasElement = doc.createElement("canvas");
  215. const context = canvasElement.getContext("2d");
  216. canvasElement.width = element.clientWidth;
  217. canvasElement.height = element.clientHeight;
  218. try {
  219. context.drawImage(element, 0, 0, canvasElement.width, canvasElement.height);
  220. data.posters.push(canvasElement.toDataURL("image/png", ""));
  221. element.setAttribute(POSTER_ATTRIBUTE_NAME, data.posters.length - 1);
  222. data.markedElements.push(element);
  223. } catch (error) {
  224. // ignored
  225. }
  226. }
  227. }
  228. if (element.tagName == "IFRAME") {
  229. if (elementHidden) {
  230. element.setAttribute("src", "data:text/html,");
  231. }
  232. }
  233. if (element.tagName == "LINK") {
  234. if (element.import) {
  235. data.imports.push({ content: serialize(element.import) });
  236. element.setAttribute(HTML_IMPORT_ATTRIBUTE_NAME, data.imports.length - 1);
  237. data.markedElements.push(element);
  238. }
  239. }
  240. if (element.tagName == "INPUT") {
  241. if (element.type != "password") {
  242. element.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, element.value);
  243. data.markedElements.push(element);
  244. }
  245. if (element.type == "radio" || element.type == "checkbox") {
  246. element.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, element.checked);
  247. data.markedElements.push(element);
  248. }
  249. }
  250. if (element.tagName == "TEXTAREA") {
  251. element.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, element.value);
  252. data.markedElements.push(element);
  253. }
  254. if (element.tagName == "SELECT") {
  255. element.querySelectorAll("option").forEach(option => {
  256. if (option.selected) {
  257. option.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, "");
  258. data.markedElements.push(option);
  259. }
  260. });
  261. }
  262. }
  263. function getUsedFont(computedStyle, options, usedFonts) {
  264. if (computedStyle) {
  265. const fontStyle = computedStyle.getPropertyValue("font-style") || "normal";
  266. computedStyle.getPropertyValue("font-family").split(",").forEach(fontFamilyName => {
  267. fontFamilyName = normalizeFontFamily(fontFamilyName);
  268. if (!options.loadedFonts || options.loadedFonts.find(font => normalizeFontFamily(font.family) == fontFamilyName && font.style == fontStyle)) {
  269. const fontWeight = getFontWeight(computedStyle.getPropertyValue("font-weight"));
  270. const fontVariant = computedStyle.getPropertyValue("font-variant") || "normal";
  271. const value = [fontFamilyName, fontWeight, fontStyle, fontVariant];
  272. usedFonts.set(JSON.stringify(value), [fontFamilyName, fontWeight, fontStyle, fontVariant]);
  273. }
  274. });
  275. }
  276. }
  277. function normalizeFontFamily(fontFamilyName) {
  278. return removeQuotes(fontFamilyName.trim()).toLowerCase();
  279. }
  280. function testHiddenElement(element, computedStyle, markedElements) {
  281. let hidden = false;
  282. if (computedStyle) {
  283. const display = computedStyle.getPropertyValue("display");
  284. const opacity = computedStyle.getPropertyValue("opacity");
  285. const visibility = computedStyle.getPropertyValue("visibility");
  286. hidden = display == "none";
  287. if (hidden) {
  288. if (element.style.getPropertyValue("display") != "none" && !IGNORED_REMOVED_TAG_NAMES.includes(element.tagName)) {
  289. element.setAttribute(HIDDEN_CONTENT_ATTRIBUTE_NAME, "");
  290. markedElements.push(element);
  291. }
  292. } else if ((opacity == "0" || visibility == "hidden") && element.getBoundingClientRect) {
  293. const boundingRect = element.getBoundingClientRect();
  294. hidden = !boundingRect.width && !boundingRect.height;
  295. }
  296. }
  297. return Boolean(hidden);
  298. }
  299. function postProcessDoc(doc, markedElements) {
  300. doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  301. const noscriptElement = doc.createElement("noscript");
  302. noscriptElement.textContent = element.innerHTML || element.textContent;
  303. element.parentElement.replaceChild(noscriptElement, element);
  304. });
  305. doc.querySelectorAll("meta[disabled-http-equiv]").forEach(element => {
  306. element.setAttribute("http-equiv", element.getAttribute("disabled-http-equiv"));
  307. element.removeAttribute("disabled-http-equiv");
  308. });
  309. if (doc.head) {
  310. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  311. }
  312. if (!markedElements) {
  313. const singleFileAttributes = [REMOVED_CONTENT_ATTRIBUTE_NAME, HIDDEN_CONTENT_ATTRIBUTE_NAME, PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, IMAGE_ATTRIBUTE_NAME, POSTER_ATTRIBUTE_NAME, CANVAS_ATTRIBUTE_NAME, INPUT_VALUE_ATTRIBUTE_NAME, SHADOW_ROOT_ATTRIBUTE_NAME, HTML_IMPORT_ATTRIBUTE_NAME, STYLESHEET_ATTRIBUTE_NAME];
  314. markedElements = doc.querySelectorAll(singleFileAttributes.map(name => "[" + name + "]").join(","));
  315. }
  316. markedElements.forEach(element => {
  317. element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME);
  318. element.removeAttribute(HIDDEN_CONTENT_ATTRIBUTE_NAME);
  319. element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME);
  320. element.removeAttribute(IMAGE_ATTRIBUTE_NAME);
  321. element.removeAttribute(POSTER_ATTRIBUTE_NAME);
  322. element.removeAttribute(CANVAS_ATTRIBUTE_NAME);
  323. element.removeAttribute(INPUT_VALUE_ATTRIBUTE_NAME);
  324. element.removeAttribute(SHADOW_ROOT_ATTRIBUTE_NAME);
  325. element.removeAttribute(HTML_IMPORT_ATTRIBUTE_NAME);
  326. element.removeAttribute(STYLESHEET_ATTRIBUTE_NAME);
  327. });
  328. }
  329. function getStylesheetsData(doc) {
  330. if (doc) {
  331. const contents = [];
  332. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  333. try {
  334. const tempStyleElement = doc.createElement("style");
  335. tempStyleElement.textContent = styleElement.textContent;
  336. doc.body.appendChild(tempStyleElement);
  337. const stylesheet = tempStyleElement.sheet;
  338. tempStyleElement.remove();
  339. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  340. styleElement.setAttribute(STYLESHEET_ATTRIBUTE_NAME, styleIndex);
  341. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(cssRule => cssRule.cssText).join("\n");
  342. }
  343. } catch (error) {
  344. // ignored
  345. }
  346. });
  347. return contents;
  348. }
  349. }
  350. function getSize(win, imageElement, computedStyle) {
  351. let pxWidth = imageElement.naturalWidth;
  352. let pxHeight = imageElement.naturalHeight;
  353. if (!pxWidth && !pxHeight) {
  354. computedStyle = computedStyle || win.getComputedStyle(imageElement);
  355. let removeBorderWidth = false;
  356. if (computedStyle.getPropertyValue("box-sizing") == "content-box") {
  357. const boxSizingValue = imageElement.style.getPropertyValue("box-sizing");
  358. const boxSizingPriority = imageElement.style.getPropertyPriority("box-sizing");
  359. const clientWidth = imageElement.clientWidth;
  360. imageElement.style.setProperty("box-sizing", "border-box", "important");
  361. removeBorderWidth = imageElement.clientWidth != clientWidth;
  362. if (boxSizingValue) {
  363. imageElement.style.setProperty("box-sizing", boxSizingValue, boxSizingPriority);
  364. } else {
  365. imageElement.style.removeProperty("box-sizing");
  366. }
  367. }
  368. let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
  369. paddingLeft = getWidth("padding-left", computedStyle);
  370. paddingRight = getWidth("padding-right", computedStyle);
  371. paddingTop = getWidth("padding-top", computedStyle);
  372. paddingBottom = getWidth("padding-bottom", computedStyle);
  373. if (removeBorderWidth) {
  374. borderLeft = getWidth("border-left-width", computedStyle);
  375. borderRight = getWidth("border-right-width", computedStyle);
  376. borderTop = getWidth("border-top-width", computedStyle);
  377. borderBottom = getWidth("border-bottom-width", computedStyle);
  378. } else {
  379. borderLeft = borderRight = borderTop = borderBottom = 0;
  380. }
  381. pxWidth = Math.max(0, imageElement.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight);
  382. pxHeight = Math.max(0, imageElement.clientHeight - paddingTop - paddingBottom - borderTop - borderBottom);
  383. }
  384. return { pxWidth, pxHeight };
  385. }
  386. function getWidth(styleName, computedStyle) {
  387. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  388. return parseFloat(computedStyle.getPropertyValue(styleName));
  389. }
  390. }
  391. function getFontsData() {
  392. if (singlefile.lib.processors.hooks.content.frames) {
  393. return singlefile.lib.processors.hooks.content.frames.getFontsData();
  394. }
  395. }
  396. function serialize(doc) {
  397. const docType = doc.doctype;
  398. let docTypeString = "";
  399. if (docType) {
  400. docTypeString = "<!DOCTYPE " + docType.nodeName;
  401. if (docType.publicId) {
  402. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  403. if (docType.systemId) {
  404. docTypeString += " \"" + docType.systemId + "\"";
  405. }
  406. } else if (docType.systemId) {
  407. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  408. } if (docType.internalSubset) {
  409. docTypeString += " [" + docType.internalSubset + "]";
  410. }
  411. docTypeString += "> ";
  412. }
  413. return docTypeString + doc.documentElement.outerHTML;
  414. }
  415. function removeQuotes(string) {
  416. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  417. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  418. } else {
  419. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  420. }
  421. return string.trim();
  422. }
  423. function getFontWeight(weight) {
  424. return FONT_WEIGHTS[weight] || weight;
  425. }
  426. })();