doc-helper.js 17 KB

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