doc-helper.js 16 KB

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