doc-helper.js 16 KB

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