doc-helper.js 16 KB

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