doc-helper.js 17 KB

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