single-file-helper.js 17 KB

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