doc-helper.js 16 KB

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