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 REMOVED_CANDIDATE_ATTRIBUTE_NAME = "data-single-file-removed-candidate";
  24. const PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME = "data-single-file-preserved-space-element";
  25. const WIN_ID_ATTRIBUTE_NAME = "data-frame-tree-win-id";
  26. const RESPONSIVE_IMAGE_ATTRIBUTE_NAME = "data-single-file-responsive-image";
  27. const IMAGE_ATTRIBUTE_NAME = "data-single-file-image";
  28. const INPUT_VALUE_ATTRIBUTE_NAME = "data-single-file-value";
  29. const SHEET_ATTRIBUTE_NAME = "data-single-file-sheet";
  30. const IGNORED_REMOVED_TAG_NAMES = ["NOSCRIPT", "DISABLED-NOSCRIPT", "META", "LINK", "STYLE", "TITLE", "TEMPLATE", "SOURCE", "OBJECT"];
  31. return {
  32. preProcessDoc,
  33. postProcessDoc,
  34. serialize,
  35. windowIdAttributeName,
  36. preservedSpaceAttributeName,
  37. removedContentAttributeName,
  38. responsiveImagesAttributeName,
  39. imagesAttributeName,
  40. inputValueAttributeName,
  41. sheetAttributeName
  42. };
  43. function preProcessDoc(doc, win, options) {
  44. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  45. doc.querySelectorAll("noscript").forEach(element => {
  46. const disabledNoscriptElement = doc.createElement("disabled-noscript");
  47. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  48. disabledNoscriptElement.hidden = true;
  49. element.parentElement.replaceChild(disabledNoscriptElement, element);
  50. });
  51. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  52. if (options.removeHiddenElements) {
  53. const markerRemovedContent = removedContentAttributeName(options.sessionId);
  54. const markerRemovedCandidate = removedCandidateAttributeName(options.sessionId);
  55. let ignoredTags = JSON.parse(JSON.stringify(IGNORED_REMOVED_TAG_NAMES));
  56. if (!options.removeFrame) {
  57. ignoredTags = ignoredTags.concat(...["IFRAME", "FRAME"]);
  58. }
  59. if (!options.removeScripts) {
  60. ignoredTags = ignoredTags.concat("SCRIPT");
  61. }
  62. if (win) {
  63. markHiddenCandidates(win, doc.body, markerRemovedContent, markerRemovedCandidate, ignoredTags);
  64. markHiddenElements(win, doc.body, markerRemovedContent);
  65. markBackdropBackground(doc, win, markerRemovedCandidate);
  66. }
  67. doc.querySelectorAll(("[" + markerRemovedCandidate + "]")).forEach(element => element.removeAttribute(markerRemovedCandidate));
  68. }
  69. if (win && options.compressHTML) {
  70. doc.querySelectorAll("*").forEach(element => {
  71. const style = win.getComputedStyle(element);
  72. if (style && style.whiteSpace.startsWith("pre")) {
  73. element.setAttribute(preservedSpaceAttributeName(options.sessionId), "");
  74. }
  75. });
  76. }
  77. retrieveInputValues(doc, options);
  78. return {
  79. canvasData: win && getCanvasData(doc, win),
  80. fontsData: getFontsData(doc),
  81. stylesheetContents: getStylesheetContents(doc),
  82. responsiveImageData: getResponsiveImageData(doc, options),
  83. imageData: win && getImageData(doc, win, options),
  84. postersData: getPostersData(doc)
  85. };
  86. }
  87. function markBackdropBackground(doc, win, markerRemovedCandidate) {
  88. const threshold = .95;
  89. const elements = doc.elementsFromPoint(win.innerWidth / 2, win.innerHeight / 2);
  90. if (elements.length > 1) {
  91. const element = elements[0];
  92. const style = win.getComputedStyle(element);
  93. const fullScreen = (element.clientWidth >= win.innerWidth * threshold) && (element.clientWidth >= win.innerWidth * threshold) && (style && style.getPropertyValue("z-index") >= 999);
  94. if (fullScreen) {
  95. element.setAttribute(markerRemovedCandidate, "");
  96. }
  97. }
  98. }
  99. function markHiddenCandidates(win, element, markerRemovedContent, markerRemovedCandidate, ignoredTags) {
  100. const elements = Array.from(element.childNodes).filter(node => node.nodeType == win.Node.ELEMENT_NODE);
  101. elements.forEach(element => markHiddenCandidates(win, element, markerRemovedContent, markerRemovedCandidate, ignoredTags));
  102. if (elements.length) {
  103. const hiddenCandidate = !elements.find(element => element.getAttribute(markerRemovedCandidate) !== "");
  104. if (hiddenCandidate) {
  105. if (hiddenElement(win, element, ignoredTags) && element instanceof win.HTMLElement) {
  106. element.setAttribute(markerRemovedCandidate, "");
  107. elements.forEach(element => {
  108. if (element instanceof win.HTMLElement) {
  109. element.setAttribute(markerRemovedContent, "");
  110. }
  111. });
  112. }
  113. }
  114. } else if (hiddenElement(win, element, ignoredTags)) {
  115. element.setAttribute(markerRemovedCandidate, "");
  116. }
  117. }
  118. function markHiddenElements(win, element, markerRemovedContent) {
  119. const elements = Array.from(element.childNodes).filter(node => node.nodeType == win.Node.ELEMENT_NODE);
  120. elements.forEach(element => markHiddenElements(win, element, markerRemovedContent));
  121. if (element.parentElement.getAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME) != "") {
  122. element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME);
  123. }
  124. }
  125. function hiddenElement(win, element, ignoredTags) {
  126. const cacheElementsHidden = new Map();
  127. const hidden = testHiddenElement(win, element, ignoredTags, cacheElementsHidden);
  128. if (!hidden) {
  129. let parentElement = element.parentElement;
  130. if (parentElement) {
  131. let parentElementHidden = testHiddenElement(win, parentElement, ignoredTags, cacheElementsHidden);
  132. while (parentElement && !parentElementHidden) {
  133. parentElement = parentElement.parentElement;
  134. if (parentElement) {
  135. parentElementHidden = testHiddenElement(win, parentElement, ignoredTags, cacheElementsHidden);
  136. }
  137. }
  138. return parentElementHidden;
  139. }
  140. }
  141. return hidden;
  142. }
  143. function testHiddenElement(win, element, ignoredTags, cacheElementsHidden) {
  144. let hidden = cacheElementsHidden.get(element);
  145. if (hidden === undefined) {
  146. if (!ignoredTags.includes(element.tagName)) {
  147. hidden = element.hidden;
  148. if (!hidden) {
  149. const elementStyle = element.style;
  150. hidden = elementStyle && elementStyle.display == "none";
  151. if (!hidden) {
  152. const style = win.getComputedStyle(element);
  153. if (style) {
  154. hidden = style.display == "none";
  155. if (!hidden && (style.opacity == "0" || style.visibility == "hidden")) {
  156. const boundingRect = element.getBoundingClientRect();
  157. hidden = !boundingRect.width && !boundingRect.height;
  158. }
  159. }
  160. }
  161. }
  162. }
  163. hidden = Boolean(hidden);
  164. cacheElementsHidden.set(element, hidden);
  165. }
  166. return hidden;
  167. }
  168. function postProcessDoc(doc, options) {
  169. doc.querySelectorAll("disabled-noscript").forEach(element => {
  170. const noscriptElement = doc.createElement("noscript");
  171. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  172. element.parentElement.replaceChild(noscriptElement, element);
  173. });
  174. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  175. if (options.removeHiddenElements) {
  176. doc.querySelectorAll("[" + removedContentAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(removedContentAttributeName(options.sessionId)));
  177. }
  178. if (options.compressHTML) {
  179. doc.querySelectorAll("[" + preservedSpaceAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(preservedSpaceAttributeName(options.sessionId)));
  180. }
  181. doc.querySelectorAll("[" + responsiveImagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(responsiveImagesAttributeName(options.sessionId)));
  182. doc.querySelectorAll("[" + imagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(imagesAttributeName(options.sessionId)));
  183. doc.querySelectorAll("[" + inputValueAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(inputValueAttributeName(options.sessionId)));
  184. }
  185. function responsiveImagesAttributeName(sessionId) {
  186. return RESPONSIVE_IMAGE_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  187. }
  188. function imagesAttributeName(sessionId) {
  189. return IMAGE_ATTRIBUTE_NAME + (sessionId || "");
  190. }
  191. function preservedSpaceAttributeName(sessionId) {
  192. return PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + (sessionId || "");
  193. }
  194. function removedContentAttributeName(sessionId) {
  195. return REMOVED_CONTENT_ATTRIBUTE_NAME + (sessionId || "");
  196. }
  197. function removedCandidateAttributeName(sessionId) {
  198. return REMOVED_CANDIDATE_ATTRIBUTE_NAME + (sessionId || "");
  199. }
  200. function windowIdAttributeName(sessionId) {
  201. return WIN_ID_ATTRIBUTE_NAME + (sessionId || "");
  202. }
  203. function inputValueAttributeName(sessionId) {
  204. return INPUT_VALUE_ATTRIBUTE_NAME + (sessionId || "");
  205. }
  206. function sheetAttributeName(sessionId) {
  207. return SHEET_ATTRIBUTE_NAME + (sessionId || "");
  208. }
  209. function getCanvasData(doc, win) {
  210. if (doc) {
  211. const canvasData = [];
  212. doc.querySelectorAll("canvas").forEach(canvasElement => {
  213. try {
  214. const size = getSize(win, canvasElement);
  215. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: size.width, height: size.height });
  216. } catch (error) {
  217. canvasData.push(null);
  218. }
  219. });
  220. return canvasData;
  221. }
  222. }
  223. function getStylesheetContents(doc) {
  224. if (doc) {
  225. const contents = [];
  226. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  227. let stylesheet;
  228. try {
  229. const tempStyleElement = doc.createElement("style");
  230. tempStyleElement.textContent = styleElement.textContent;
  231. doc.body.appendChild(tempStyleElement);
  232. stylesheet = tempStyleElement.sheet;
  233. tempStyleElement.remove();
  234. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  235. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n");
  236. }
  237. } catch (error) {
  238. /* ignored */
  239. }
  240. });
  241. return contents;
  242. }
  243. }
  244. function getImageData(doc, win, options) {
  245. if (doc) {
  246. const data = [];
  247. doc.querySelectorAll("img[src]:not([srcset])").forEach((imageElement, imageElementIndex) => {
  248. const computedStyle = win.getComputedStyle(imageElement);
  249. let imageData = {}, size = getSize(win, imageElement);
  250. if (imageElement.src && size && (!computedStyle.getPropertyValue("background-image") || computedStyle.getPropertyValue("background-image") == "none")) {
  251. imageElement.setAttribute(imagesAttributeName(options.sessionId), imageElementIndex);
  252. imageData = size;
  253. }
  254. data.push(imageData);
  255. });
  256. return data;
  257. }
  258. }
  259. function getSize(win, imageElement) {
  260. const boxSizing = imageElement.style.getPropertyValue("box-sizing");
  261. const boxSizingImportant = imageElement.style.getPropertyPriority("box-sizing");
  262. imageElement.style.setProperty("box-sizing", "border-box", "important");
  263. const computedStyle = win.getComputedStyle(imageElement);
  264. const paddingLeft = getWidth("padding-left", computedStyle);
  265. const paddingRight = getWidth("padding-right", computedStyle);
  266. const paddingTop = getWidth("padding-top", computedStyle);
  267. const paddingBottom = getWidth("padding-bottom", computedStyle);
  268. const width = imageElement.clientWidth;
  269. const height = imageElement.clientHeight;
  270. if (boxSizing) {
  271. imageElement.style.setProperty("box-sizing", boxSizing, boxSizingImportant);
  272. } else {
  273. imageElement.style.removeProperty("box-sizing");
  274. }
  275. if (width >= 0 && height >= 0 && paddingLeft >= 0 && paddingRight >= 0 && paddingTop >= 0 && paddingBottom >= 0) {
  276. return {
  277. width: (paddingLeft || paddingRight) && (width - paddingLeft - paddingRight) + "px",
  278. pxWidth: Math.round(width - paddingLeft - paddingRight),
  279. height: (paddingLeft || paddingRight) && (height - paddingTop - paddingBottom) + "px",
  280. pxHeight: Math.round(height - paddingTop - paddingBottom),
  281. };
  282. }
  283. }
  284. function getWidth(styleName, computedStyle) {
  285. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  286. return parseFloat(computedStyle.getPropertyValue(styleName));
  287. }
  288. }
  289. function getResponsiveImageData(doc, options) {
  290. if (doc) {
  291. const data = [];
  292. doc.querySelectorAll("picture, img[srcset]").forEach((element, elementIndex) => {
  293. const tagName = element.tagName.toLowerCase();
  294. let imageData = {}, imageElement;
  295. element.setAttribute(responsiveImagesAttributeName(options.sessionId), elementIndex);
  296. if (tagName == "picture") {
  297. const sources = Array.from(element.querySelectorAll("source")).map(sourceElement => (
  298. { src: sourceElement.src, srcset: sourceElement.srcset }
  299. ));
  300. imageElement = element.querySelector("img");
  301. imageData.sources = sources;
  302. }
  303. if (tagName == "img") {
  304. imageElement = element;
  305. }
  306. if (imageElement) {
  307. let naturalWidth = imageElement.naturalWidth, naturalHeight = imageElement.naturalHeight;
  308. if (naturalWidth <= 1 && naturalHeight <= 1) {
  309. const imgElement = doc.createElement("img");
  310. imgElement.src = imageElement.src;
  311. doc.body.appendChild(imgElement);
  312. naturalWidth = imgElement.width;
  313. naturalHeight = imgElement.height;
  314. imgElement.remove();
  315. }
  316. imageData.source = {
  317. clientWidth: imageElement.clientWidth,
  318. clientHeight: imageElement.clientHeight,
  319. naturalWidth: naturalWidth,
  320. naturalHeight: naturalHeight,
  321. width: imageElement.width,
  322. height: imageElement.height,
  323. src: (!imageElement.currentSrc.startsWith("data:") && imageElement.currentSrc) || (!imageElement.src.startsWith("data:") && imageElement.src)
  324. };
  325. }
  326. data.push(imageData);
  327. });
  328. return data;
  329. }
  330. }
  331. function getPostersData(doc) {
  332. if (doc) {
  333. const postersData = [];
  334. doc.querySelectorAll("video").forEach(videoElement => {
  335. if (videoElement.poster) {
  336. postersData.push(null);
  337. } else {
  338. const canvasElement = doc.createElement("canvas");
  339. const context = canvasElement.getContext("2d");
  340. canvasElement.width = videoElement.clientWidth;
  341. canvasElement.height = videoElement.clientHeight;
  342. try {
  343. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  344. postersData.push(canvasElement.toDataURL("image/png", ""));
  345. } catch (error) {
  346. postersData.push(null);
  347. }
  348. }
  349. });
  350. return postersData;
  351. }
  352. }
  353. function getFontsData() {
  354. if (typeof fontFaceProxy != "undefined") {
  355. return fontFaceProxy.getFontsData();
  356. }
  357. }
  358. function retrieveInputValues(doc, options) {
  359. doc.querySelectorAll("input").forEach(input => input.setAttribute(inputValueAttributeName(options.sessionId), input.value));
  360. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(inputValueAttributeName(options.sessionId), textarea.value));
  361. doc.querySelectorAll("select").forEach(select => {
  362. select.querySelectorAll("option").forEach(option => {
  363. if (option.selected) {
  364. option.setAttribute(inputValueAttributeName(options.sessionId), "");
  365. }
  366. });
  367. });
  368. }
  369. function serialize(doc) {
  370. const docType = doc.doctype;
  371. let docTypeString = "";
  372. if (docType) {
  373. docTypeString = "<!DOCTYPE " + docType.nodeName;
  374. if (docType.publicId) {
  375. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  376. if (docType.systemId) {
  377. docTypeString += " \"" + docType.systemId + "\"";
  378. }
  379. } else if (docType.systemId) {
  380. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  381. } if (docType.internalSubset) {
  382. docTypeString += " [" + docType.internalSubset + "]";
  383. }
  384. docTypeString += "> ";
  385. }
  386. return docTypeString + doc.documentElement.outerHTML;
  387. }
  388. })();