doc-helper.js 17 KB

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