doc-helper.js 17 KB

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