doc-helper.js 18 KB

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