doc-helper.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 RESPONSIVE_IMAGE_ATTRIBUTE_NAME = "data-single-file-responsive-image";
  26. const IMAGE_ATTRIBUTE_NAME = "data-single-file-image";
  27. const INPUT_VALUE_ATTRIBUTE_NAME = "data-single-file-value";
  28. const SHEET_ATTRIBUTE_NAME = "data-single-file-sheet";
  29. const IGNORED_REMOVED_TAG_NAMES = ["NOSCRIPT", "DISABLED-NOSCRIPT", "META", "LINK", "STYLE", "TITLE", "TEMPLATE", "SOURCE", "OBJECT"];
  30. const MASK_TAGNAME = "singlefile-mask";
  31. const BACKDROP_THRESHOLD_SIZE = .95;
  32. const BACKDROP_THRESHOLD_ZINDEX = 999;
  33. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  34. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  35. const FONT_WEIGHTS = {
  36. normal: "400",
  37. bold: "700"
  38. };
  39. return {
  40. preProcessDoc,
  41. postProcessDoc,
  42. serialize,
  43. windowIdAttributeName,
  44. preservedSpaceAttributeName,
  45. removedContentAttributeName,
  46. responsiveImagesAttributeName,
  47. imagesAttributeName,
  48. inputValueAttributeName,
  49. sheetAttributeName
  50. };
  51. function preProcessDoc(doc, win, options) {
  52. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  53. doc.querySelectorAll("noscript").forEach(element => {
  54. const disabledNoscriptElement = doc.createElement("disabled-noscript");
  55. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  56. disabledNoscriptElement.hidden = true;
  57. element.parentElement.replaceChild(disabledNoscriptElement, element);
  58. });
  59. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  60. let canvasData, imageData, usedFonts;
  61. if (win) {
  62. canvasData = getCanvasData(doc, win);
  63. imageData = getImageData(doc, win, options);
  64. if (options.removeHiddenElements || options.removeAlternativeFonts || options.compressHTML) {
  65. const styles = getStyles(win, doc.body);
  66. if (options.removeHiddenElements) {
  67. const markerRemovedContent = removedContentAttributeName(options.sessionId);
  68. let ignoredTags = JSON.parse(JSON.stringify(IGNORED_REMOVED_TAG_NAMES));
  69. if (!options.removeScripts) {
  70. ignoredTags = ignoredTags.concat("SCRIPT");
  71. }
  72. markHiddenCandidates(win, doc.body, styles, false, markerRemovedContent, new Set(), ignoredTags);
  73. markHiddenElements(win, doc.body, styles, markerRemovedContent);
  74. markBackdropBackground(doc, win, markerRemovedContent);
  75. doc.querySelectorAll("iframe").forEach(element => {
  76. const boundingRect = element.getBoundingClientRect();
  77. if (!boundingRect.width && !boundingRect.height) {
  78. element.setAttribute(markerRemovedContent, "");
  79. }
  80. });
  81. }
  82. if (options.removeAlternativeFonts) {
  83. usedFonts = getUsedFonts(styles);
  84. }
  85. if (options.compressHTML) {
  86. styles.forEach((style, element) => {
  87. if (style.whiteSpace.startsWith("pre")) {
  88. element.setAttribute(preservedSpaceAttributeName(options.sessionId), "");
  89. }
  90. });
  91. }
  92. }
  93. }
  94. retrieveInputValues(doc, options);
  95. return {
  96. canvasData,
  97. fontsData: getFontsData(doc),
  98. stylesheetContents: getStylesheetContents(doc),
  99. responsiveImageData: getResponsiveImageData(doc, options),
  100. imageData,
  101. postersData: getPostersData(doc),
  102. usedFonts
  103. };
  104. }
  105. function getUsedFonts(styles) {
  106. const usedFonts = new Set();
  107. styles.forEach(style => {
  108. const fontFamilyNames = style.fontFamily.split(",");
  109. fontFamilyNames.forEach(fontFamilyName => {
  110. style.fontFamily = removeQuotes(fontFamilyName);
  111. usedFonts.add(getFontKey(style));
  112. });
  113. });
  114. return Array.from(usedFonts).map(key => {
  115. const [fontFamily, fontWeight, fontStyle, fontVariant] = JSON.parse(key);
  116. return { fontFamily, fontWeight, fontStyle, fontVariant };
  117. });
  118. }
  119. function markBackdropBackground(doc, win, markerRemovedContent) {
  120. const threshold = BACKDROP_THRESHOLD_SIZE;
  121. let elements = getCandidateElements();
  122. let fullScreen = true;
  123. while (elements.length > 1 && fullScreen) {
  124. elements = getCandidateElements();
  125. const element = elements[0];
  126. const style = win.getComputedStyle(element);
  127. fullScreen = (element.clientWidth >= win.innerWidth * threshold) && (element.clientHeight >= win.innerHeight * threshold) && (style && style.getPropertyValue("z-index") >= BACKDROP_THRESHOLD_ZINDEX);
  128. if (fullScreen) {
  129. element.setAttribute(markerRemovedContent, "");
  130. }
  131. }
  132. function getCandidateElements() {
  133. return Array.from(doc.elementsFromPoint(win.innerWidth / 2, win.innerHeight / 2)).filter(element => element.tagName.toLowerCase() != MASK_TAGNAME && element.getAttribute(markerRemovedContent) == null);
  134. }
  135. }
  136. function getStyles(win, element, styles = new Map()) {
  137. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  138. elements.forEach(element => {
  139. getStyles(win, element, styles);
  140. const computedStyle = win.getComputedStyle(element);
  141. styles.set(element, {
  142. display: computedStyle.display,
  143. opacity: computedStyle.opacity,
  144. visibility: computedStyle.visibility,
  145. fontFamily: computedStyle.fontFamily,
  146. fontWeight: getFontWeight(computedStyle.fontWeight),
  147. fontStyle: computedStyle.fontStyle || "normal",
  148. fontVariant: computedStyle.fontVariant || "normal",
  149. whiteSpace: computedStyle.whiteSpace
  150. });
  151. });
  152. return styles;
  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, styles, 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. styles.delete(element);
  174. elements.forEach(element => markHiddenElements(win, element, styles, markerRemovedContent));
  175. }
  176. }
  177. function testHiddenElement(element, style) {
  178. let hidden = element.hidden;
  179. if (!hidden && style) {
  180. hidden = style.display == "none";
  181. if (!hidden && (style.opacity == "0" || style.visibility == "hidden")) {
  182. const boundingRect = element.getBoundingClientRect();
  183. hidden = !boundingRect.width && !boundingRect.height;
  184. }
  185. }
  186. return Boolean(hidden);
  187. }
  188. function postProcessDoc(doc, options) {
  189. doc.querySelectorAll("disabled-noscript").forEach(element => {
  190. const noscriptElement = doc.createElement("noscript");
  191. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  192. element.parentElement.replaceChild(noscriptElement, element);
  193. });
  194. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  195. if (options.removeHiddenElements) {
  196. doc.querySelectorAll("[" + removedContentAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(removedContentAttributeName(options.sessionId)));
  197. }
  198. if (options.compressHTML) {
  199. doc.querySelectorAll("[" + preservedSpaceAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(preservedSpaceAttributeName(options.sessionId)));
  200. }
  201. doc.querySelectorAll("[" + responsiveImagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(responsiveImagesAttributeName(options.sessionId)));
  202. doc.querySelectorAll("[" + imagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(imagesAttributeName(options.sessionId)));
  203. doc.querySelectorAll("[" + inputValueAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(inputValueAttributeName(options.sessionId)));
  204. }
  205. function responsiveImagesAttributeName(sessionId) {
  206. return RESPONSIVE_IMAGE_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  207. }
  208. function imagesAttributeName(sessionId) {
  209. return IMAGE_ATTRIBUTE_NAME + (sessionId || "");
  210. }
  211. function preservedSpaceAttributeName(sessionId) {
  212. return PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + (sessionId || "");
  213. }
  214. function removedContentAttributeName(sessionId) {
  215. return REMOVED_CONTENT_ATTRIBUTE_NAME + (sessionId || "");
  216. }
  217. function windowIdAttributeName(sessionId) {
  218. return WIN_ID_ATTRIBUTE_NAME + (sessionId || "");
  219. }
  220. function inputValueAttributeName(sessionId) {
  221. return INPUT_VALUE_ATTRIBUTE_NAME + (sessionId || "");
  222. }
  223. function sheetAttributeName(sessionId) {
  224. return SHEET_ATTRIBUTE_NAME + (sessionId || "");
  225. }
  226. function getCanvasData(doc, win) {
  227. if (doc) {
  228. const canvasData = [];
  229. doc.querySelectorAll("canvas").forEach(canvasElement => {
  230. try {
  231. const size = getSize(win, canvasElement);
  232. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: size.width, height: size.height });
  233. } catch (error) {
  234. canvasData.push(null);
  235. }
  236. });
  237. return canvasData;
  238. }
  239. }
  240. function getStylesheetContents(doc) {
  241. if (doc) {
  242. const contents = [];
  243. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  244. let stylesheet;
  245. try {
  246. const tempStyleElement = doc.createElement("style");
  247. tempStyleElement.textContent = styleElement.textContent;
  248. doc.body.appendChild(tempStyleElement);
  249. stylesheet = tempStyleElement.sheet;
  250. tempStyleElement.remove();
  251. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  252. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n");
  253. }
  254. } catch (error) {
  255. /* ignored */
  256. }
  257. });
  258. return contents;
  259. }
  260. }
  261. function getImageData(doc, win, options) {
  262. if (doc) {
  263. const data = [];
  264. doc.querySelectorAll("img").forEach((imageElement, imageElementIndex) => {
  265. imageElement.setAttribute(imagesAttributeName(options.sessionId), imageElementIndex);
  266. const imageData = {
  267. src: imageElement.currentSrc || imageElement.src
  268. };
  269. const computedStyle = win.getComputedStyle(imageElement);
  270. if (computedStyle) {
  271. imageData.size = getSize(win, imageElement);
  272. imageData.empty = imageElement.naturalWidth <= 1 && imageElement.naturalHeight <= 1;
  273. if ((!computedStyle.getPropertyValue("background-image") || computedStyle.getPropertyValue("background-image") == "none") && imageData.size.pxWidth > 1 && imageData.size.pxHeight > 1) {
  274. imageData.replaceable = true;
  275. imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
  276. imageData.objectFit = computedStyle.getPropertyValue("object-fit");
  277. imageData.objectPosition = computedStyle.getPropertyValue("object-position");
  278. }
  279. }
  280. data.push(imageData);
  281. });
  282. return data;
  283. }
  284. }
  285. function getSize(win, imageElement) {
  286. const computedStyle = win.getComputedStyle(imageElement);
  287. let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
  288. paddingLeft = getWidth("padding-left", computedStyle);
  289. paddingRight = getWidth("padding-right", computedStyle);
  290. paddingTop = getWidth("padding-top", computedStyle);
  291. paddingBottom = getWidth("padding-bottom", computedStyle);
  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. const width = imageElement.clientWidth;
  297. const height = imageElement.clientHeight;
  298. if (width >= 0 && height >= 0 && paddingLeft >= 0 && paddingRight >= 0 && paddingTop >= 0 && paddingBottom >= 0 && borderLeft >= 0 && borderRight >= 0 && borderTop >= 0 && borderBottom >= 0) {
  299. return {
  300. width: (paddingLeft || paddingRight || borderLeft || borderRight) && (width - paddingLeft - paddingRight - borderLeft - borderRight) + "px",
  301. pxWidth: width - paddingLeft - paddingRight - borderLeft - borderRight,
  302. height: (paddingTop || paddingBottom || borderTop || borderBottom) && (height - paddingTop - paddingBottom - borderTop - borderBottom) + "px",
  303. pxHeight: height - paddingTop - paddingBottom - borderTop - borderBottom,
  304. };
  305. }
  306. }
  307. function getWidth(styleName, computedStyle) {
  308. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  309. return parseFloat(computedStyle.getPropertyValue(styleName));
  310. }
  311. }
  312. function getResponsiveImageData(doc, options) {
  313. if (doc) {
  314. const data = [];
  315. doc.querySelectorAll("picture, img[srcset]").forEach((element, elementIndex) => {
  316. const tagName = element.tagName.toLowerCase();
  317. let imageData = {}, imageElement;
  318. element.setAttribute(responsiveImagesAttributeName(options.sessionId), elementIndex);
  319. if (tagName == "picture") {
  320. const sources = Array.from(element.querySelectorAll("source")).map(sourceElement => (
  321. { src: sourceElement.src, srcset: sourceElement.srcset }
  322. ));
  323. imageElement = element.querySelector("img");
  324. imageData.sources = sources;
  325. }
  326. if (tagName == "img") {
  327. imageElement = element;
  328. }
  329. if (imageElement) {
  330. let naturalWidth = imageElement.naturalWidth, naturalHeight = imageElement.naturalHeight;
  331. if (naturalWidth <= 1 && naturalHeight <= 1) {
  332. const imgElement = doc.createElement("img");
  333. imgElement.src = imageElement.src;
  334. doc.body.appendChild(imgElement);
  335. naturalWidth = imgElement.width;
  336. naturalHeight = imgElement.height;
  337. imgElement.remove();
  338. }
  339. if (naturalWidth > 1 && naturalHeight > 1) {
  340. imageData.src = (!imageElement.currentSrc.startsWith("data:") && imageElement.currentSrc) || (!imageElement.src.startsWith("data:") && imageElement.src);
  341. imageData.srcset = imageElement.srcset;
  342. }
  343. }
  344. data.push(imageData);
  345. });
  346. return data;
  347. }
  348. }
  349. function getPostersData(doc) {
  350. if (doc) {
  351. const postersData = [];
  352. doc.querySelectorAll("video").forEach(videoElement => {
  353. if (videoElement.poster) {
  354. postersData.push(null);
  355. } else {
  356. const canvasElement = doc.createElement("canvas");
  357. const context = canvasElement.getContext("2d");
  358. canvasElement.width = videoElement.clientWidth;
  359. canvasElement.height = videoElement.clientHeight;
  360. try {
  361. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  362. postersData.push(canvasElement.toDataURL("image/png", ""));
  363. } catch (error) {
  364. postersData.push(null);
  365. }
  366. }
  367. });
  368. return postersData;
  369. }
  370. }
  371. function getFontsData() {
  372. if (typeof fontFaceProxy != "undefined") {
  373. return fontFaceProxy.getFontsData();
  374. }
  375. }
  376. function retrieveInputValues(doc, options) {
  377. doc.querySelectorAll("input").forEach(input => input.setAttribute(inputValueAttributeName(options.sessionId), input.value));
  378. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(inputValueAttributeName(options.sessionId), textarea.value));
  379. doc.querySelectorAll("select").forEach(select => {
  380. select.querySelectorAll("option").forEach(option => {
  381. if (option.selected) {
  382. option.setAttribute(inputValueAttributeName(options.sessionId), "");
  383. }
  384. });
  385. });
  386. }
  387. function serialize(doc) {
  388. const docType = doc.doctype;
  389. let docTypeString = "";
  390. if (docType) {
  391. docTypeString = "<!DOCTYPE " + docType.nodeName;
  392. if (docType.publicId) {
  393. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  394. if (docType.systemId) {
  395. docTypeString += " \"" + docType.systemId + "\"";
  396. }
  397. } else if (docType.systemId) {
  398. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  399. } if (docType.internalSubset) {
  400. docTypeString += " [" + docType.internalSubset + "]";
  401. }
  402. docTypeString += "> ";
  403. }
  404. return docTypeString + doc.documentElement.outerHTML;
  405. }
  406. function getFontKey(style) {
  407. return JSON.stringify([
  408. style.fontFamily,
  409. style.fontWeight,
  410. style.fontStyle,
  411. style.fontVariant
  412. ]);
  413. }
  414. function removeQuotes(string) {
  415. string = string.toLowerCase().trim();
  416. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  417. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  418. } else {
  419. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  420. }
  421. return string.trim();
  422. }
  423. function getFontWeight(weight) {
  424. return FONT_WEIGHTS[weight] || weight;
  425. }
  426. })();