doc-helper.js 16 KB

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