doc-helper.js 15 KB

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