doc-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. * 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, elementsInfo, 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.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 (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 (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. const computedStyle = win.getComputedStyle(element);
  151. elementsInfo.set(element, {
  152. display: computedStyle.getPropertyValue("display"),
  153. opacity: computedStyle.getPropertyValue("opacity"),
  154. visibility: computedStyle.getPropertyValue("visibility"),
  155. fontFamily: computedStyle.getPropertyValue("font-family"),
  156. fontWeight: getFontWeight(computedStyle.getPropertyValue("font-weight")),
  157. fontStyle: computedStyle.getPropertyValue("font-style") || "normal",
  158. fontVariant: computedStyle.getPropertyValue("font-variant") || "normal",
  159. whiteSpace: computedStyle.getPropertyValue("white-space"),
  160. shadowRoot: element.shadowRoot
  161. });
  162. });
  163. return elementsInfo;
  164. }
  165. function markHiddenCandidates(win, element, styles, elementHidden, removedCandidates, ignoredTags) {
  166. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  167. elements.forEach(element => markHiddenCandidates(win, element, styles, elementHidden || testHiddenElement(element, styles.get(element)), removedCandidates, ignoredTags));
  168. if (elementHidden && !ignoredTags.includes(element.tagName)) {
  169. if (elements.length) {
  170. if (!elements.find(element => !removedCandidates.has(element))) {
  171. removedCandidates.add(element);
  172. elements.forEach(element => element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, ""));
  173. }
  174. } else {
  175. removedCandidates.add(element);
  176. }
  177. }
  178. }
  179. function markHiddenElements(win, element, styles, imageData) {
  180. const elements = Array.from(element.childNodes).filter(node => node.nodeType == win.Node.ELEMENT_NODE);
  181. if (element.getAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME) == "") {
  182. element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME);
  183. if (element.tagName == "IMG") {
  184. const imgData = imageData[Number(element.getAttribute(IMAGE_ATTRIBUTE_NAME))];
  185. if (imgData) {
  186. imgData.currentSrc = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  187. }
  188. }
  189. } else {
  190. elements.forEach(element => markHiddenElements(win, element, styles, imageData));
  191. }
  192. }
  193. function testHiddenElement(element, style) {
  194. let hidden = false;
  195. if (style) {
  196. hidden = style.display == "none";
  197. if (!hidden && (style.opacity == "0" || style.visibility == "hidden") && element.getBoundingClientRect) {
  198. const boundingRect = element.getBoundingClientRect();
  199. hidden = !boundingRect.width && !boundingRect.height;
  200. }
  201. }
  202. return Boolean(hidden);
  203. }
  204. function postProcessDoc(doc, options) {
  205. doc.querySelectorAll("disabled-noscript").forEach(element => {
  206. const noscriptElement = doc.createElement("noscript");
  207. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  208. element.parentElement.replaceChild(noscriptElement, element);
  209. });
  210. doc.querySelectorAll("meta[disabled-http-equiv]").forEach(element => {
  211. element.setAttribute("http-equiv", element.getAttribute("disabled-http-equiv"));
  212. element.removeAttribute("disabled-http-equiv");
  213. });
  214. if (doc.head) {
  215. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  216. }
  217. if (options.removeHiddenElements) {
  218. doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  219. }
  220. if (options.compressHTML) {
  221. doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  222. }
  223. doc.querySelectorAll("[" + IMAGE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(IMAGE_ATTRIBUTE_NAME));
  224. doc.querySelectorAll("[" + INPUT_VALUE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(INPUT_VALUE_ATTRIBUTE_NAME));
  225. doc.querySelectorAll("[" + SHADOW_ROOT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(SHADOW_ROOT_ATTRIBUTE_NAME));
  226. }
  227. function getCanvasData(doc, win) {
  228. if (doc) {
  229. const canvasData = [];
  230. doc.querySelectorAll("canvas").forEach(canvasElement => {
  231. try {
  232. const size = getSize(win, canvasElement);
  233. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: size.width, height: size.height });
  234. } catch (error) {
  235. canvasData.push(null);
  236. }
  237. });
  238. return canvasData;
  239. }
  240. }
  241. function getStylesheetContents(doc) {
  242. if (doc) {
  243. const contents = [];
  244. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  245. let stylesheet;
  246. try {
  247. const tempStyleElement = doc.createElement("style");
  248. tempStyleElement.textContent = styleElement.textContent;
  249. doc.body.appendChild(tempStyleElement);
  250. stylesheet = tempStyleElement.sheet;
  251. tempStyleElement.remove();
  252. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  253. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(cssRule => cssRule.cssText).join("\n");
  254. }
  255. } catch (error) {
  256. /* ignored */
  257. }
  258. });
  259. return contents;
  260. }
  261. }
  262. function getImageData(doc, win, options) {
  263. if (doc) {
  264. const data = [];
  265. doc.querySelectorAll("img").forEach((imageElement, imageElementIndex) => {
  266. imageElement.setAttribute(IMAGE_ATTRIBUTE_NAME, imageElementIndex);
  267. const imageData = {
  268. currentSrc: (options.loadDeferredImages && imageElement.getAttribute(LAZY_SRC_ATTRIBUTE_NAME)) || imageElement.currentSrc
  269. };
  270. imageElement.removeAttribute(LAZY_SRC_ATTRIBUTE_NAME);
  271. const computedStyle = win.getComputedStyle(imageElement);
  272. if (computedStyle) {
  273. imageData.size = getSize(win, imageElement);
  274. if ((!computedStyle.getPropertyValue("box-shadow") || computedStyle.getPropertyValue("box-shadow") == "none") &&
  275. (!computedStyle.getPropertyValue("background-image") || computedStyle.getPropertyValue("background-image") == "none") &&
  276. (imageData.size.pxWidth > 1 || imageData.size.pxHeight > 1)) {
  277. imageData.replaceable = true;
  278. imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
  279. imageData.objectFit = computedStyle.getPropertyValue("object-fit");
  280. imageData.boxSizing = computedStyle.getPropertyValue("box-sizing");
  281. imageData.objectPosition = computedStyle.getPropertyValue("object-position");
  282. }
  283. }
  284. data.push(imageData);
  285. });
  286. return data;
  287. }
  288. }
  289. function getSize(win, imageElement) {
  290. let pxWidth = imageElement.naturalWidth;
  291. let pxHeight = imageElement.naturalHeight;
  292. if (!pxWidth && !pxHeight) {
  293. const computedStyle = win.getComputedStyle(imageElement);
  294. let removeBorderWidth = false;
  295. if (computedStyle.getPropertyValue("box-sizing") == "content-box") {
  296. const boxSizingValue = imageElement.style.getPropertyValue("box-sizing");
  297. const boxSizingPriority = imageElement.style.getPropertyPriority("box-sizing");
  298. const clientWidth = imageElement.clientWidth;
  299. imageElement.style.setProperty("box-sizing", "border-box", "important");
  300. removeBorderWidth = imageElement.clientWidth != clientWidth;
  301. if (boxSizingValue) {
  302. imageElement.style.setProperty("box-sizing", boxSizingValue, boxSizingPriority);
  303. } else {
  304. imageElement.style.removeProperty("box-sizing");
  305. }
  306. }
  307. let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
  308. paddingLeft = getWidth("padding-left", computedStyle);
  309. paddingRight = getWidth("padding-right", computedStyle);
  310. paddingTop = getWidth("padding-top", computedStyle);
  311. paddingBottom = getWidth("padding-bottom", computedStyle);
  312. if (removeBorderWidth) {
  313. borderLeft = getWidth("border-left-width", computedStyle);
  314. borderRight = getWidth("border-right-width", computedStyle);
  315. borderTop = getWidth("border-top-width", computedStyle);
  316. borderBottom = getWidth("border-bottom-width", computedStyle);
  317. } else {
  318. borderLeft = borderRight = borderTop = borderBottom = 0;
  319. }
  320. pxWidth = Math.max(0, imageElement.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight);
  321. pxHeight = Math.max(0, imageElement.clientHeight - paddingTop - paddingBottom - borderTop - borderBottom);
  322. }
  323. return { pxWidth, pxHeight };
  324. }
  325. function getWidth(styleName, computedStyle) {
  326. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  327. return parseFloat(computedStyle.getPropertyValue(styleName));
  328. }
  329. }
  330. function getPostersData(doc) {
  331. if (doc) {
  332. const postersData = [];
  333. doc.querySelectorAll("video").forEach(videoElement => {
  334. if (videoElement.poster) {
  335. postersData.push(null);
  336. } else {
  337. const canvasElement = doc.createElement("canvas");
  338. const context = canvasElement.getContext("2d");
  339. canvasElement.width = videoElement.clientWidth;
  340. canvasElement.height = videoElement.clientHeight;
  341. try {
  342. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  343. postersData.push(canvasElement.toDataURL("image/png", ""));
  344. } catch (error) {
  345. postersData.push(null);
  346. }
  347. }
  348. });
  349. return postersData;
  350. }
  351. }
  352. function getFontsData() {
  353. if (typeof hooksFrame != "undefined") {
  354. return hooksFrame.getFontsData();
  355. }
  356. }
  357. function retrieveInputValues(doc) {
  358. doc.querySelectorAll("input").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.value));
  359. doc.querySelectorAll("input[type=radio], input[type=checkbox]").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.checked));
  360. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, textarea.value));
  361. doc.querySelectorAll("select").forEach(select => {
  362. select.querySelectorAll("option").forEach(option => {
  363. if (option.selected) {
  364. option.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, "");
  365. }
  366. });
  367. });
  368. }
  369. function serialize(doc) {
  370. const docType = doc.doctype;
  371. let docTypeString = "";
  372. if (docType) {
  373. docTypeString = "<!DOCTYPE " + docType.nodeName;
  374. if (docType.publicId) {
  375. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  376. if (docType.systemId) {
  377. docTypeString += " \"" + docType.systemId + "\"";
  378. }
  379. } else if (docType.systemId) {
  380. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  381. } if (docType.internalSubset) {
  382. docTypeString += " [" + docType.internalSubset + "]";
  383. }
  384. docTypeString += "> ";
  385. }
  386. return docTypeString + doc.documentElement.outerHTML;
  387. }
  388. function removeQuotes(string) {
  389. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  390. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  391. } else {
  392. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  393. }
  394. return string.trim();
  395. }
  396. function getFontWeight(weight) {
  397. return FONT_WEIGHTS[weight] || weight;
  398. }
  399. })();