doc-helper.js 16 KB

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