doc-helper.js 18 KB

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