doc-helper.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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, getComputedStyle, Node */
  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. }
  66. doc.querySelectorAll(("[" + markerRemovedCandidate + "]")).forEach(element => element.removeAttribute(markerRemovedCandidate));
  67. }
  68. if (win && options.compressHTML) {
  69. doc.querySelectorAll("*").forEach(element => {
  70. const style = win.getComputedStyle(element);
  71. if (style && style.whiteSpace.startsWith("pre")) {
  72. element.setAttribute(preservedSpaceAttributeName(options.sessionId), "");
  73. }
  74. });
  75. }
  76. retrieveInputValues(doc, options);
  77. return {
  78. canvasData: getCanvasData(doc),
  79. fontsData: getFontsData(doc),
  80. stylesheetContents: getStylesheetContents(doc),
  81. responsiveImageData: getResponsiveImageData(doc, options),
  82. imageData: getImageData(doc, options),
  83. postersData: getPostersData(doc)
  84. };
  85. }
  86. function markHiddenCandidates(win, element, markerRemovedContent, markerRemovedCandidateStage, ignoredTags) {
  87. const elements = Array.from(element.childNodes).filter(node => node.nodeType == Node.ELEMENT_NODE);
  88. elements.forEach(element => markHiddenCandidates(win, element, markerRemovedContent, markerRemovedCandidateStage, ignoredTags));
  89. if (elements.length) {
  90. const hiddenCandidate = !elements.find(element => element.getAttribute(markerRemovedCandidateStage) !== "");
  91. if (hiddenCandidate) {
  92. if (hiddenElement(element, ignoredTags) && element instanceof win.HTMLElement) {
  93. element.setAttribute(markerRemovedCandidateStage, "");
  94. elements.forEach(element => {
  95. if (element instanceof win.HTMLElement) {
  96. element.setAttribute(markerRemovedContent, "");
  97. }
  98. });
  99. }
  100. }
  101. } else if (hiddenElement(element, ignoredTags)) {
  102. element.setAttribute(markerRemovedCandidateStage, "");
  103. }
  104. }
  105. function markHiddenElements(win, element, markerRemovedContent) {
  106. const elements = Array.from(element.childNodes).filter(node => node.nodeType == Node.ELEMENT_NODE);
  107. elements.forEach(element => markHiddenElements(win, element, markerRemovedContent));
  108. if (element.parentElement.getAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME) != "") {
  109. element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME);
  110. }
  111. }
  112. function hiddenElement(element, ignoredTags) {
  113. if (ignoredTags.includes(element.tagName)) {
  114. return false;
  115. } else {
  116. let hidden = element.hidden || (element.style && (element.style.display == "none" || element.style.opacity == "0" || element.style.visibility == "hidden"));
  117. if (!hidden) {
  118. const boundingRect = element.getBoundingClientRect();
  119. hidden = !boundingRect.width && !boundingRect.height;
  120. }
  121. return hidden;
  122. }
  123. }
  124. function postProcessDoc(doc, options) {
  125. doc.querySelectorAll("disabled-noscript").forEach(element => {
  126. const noscriptElement = doc.createElement("noscript");
  127. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  128. element.parentElement.replaceChild(noscriptElement, element);
  129. });
  130. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  131. if (options.removeHiddenElements) {
  132. doc.querySelectorAll("[" + removedContentAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(removedContentAttributeName(options.sessionId)));
  133. }
  134. if (options.compressHTML) {
  135. doc.querySelectorAll("[" + preservedSpaceAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(preservedSpaceAttributeName(options.sessionId)));
  136. }
  137. doc.querySelectorAll("[" + responsiveImagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(responsiveImagesAttributeName(options.sessionId)));
  138. doc.querySelectorAll("[" + imagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(imagesAttributeName(options.sessionId)));
  139. doc.querySelectorAll("[" + inputValueAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(inputValueAttributeName(options.sessionId)));
  140. }
  141. function responsiveImagesAttributeName(sessionId) {
  142. return RESPONSIVE_IMAGE_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  143. }
  144. function imagesAttributeName(sessionId) {
  145. return IMAGE_ATTRIBUTE_NAME + (sessionId || "");
  146. }
  147. function preservedSpaceAttributeName(sessionId) {
  148. return PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + (sessionId || "");
  149. }
  150. function removedContentAttributeName(sessionId) {
  151. return REMOVED_CONTENT_ATTRIBUTE_NAME + (sessionId || "");
  152. }
  153. function removedCandidateAttributeName(sessionId) {
  154. return REMOVED_CANDIDATE_ATTRIBUTE_NAME + (sessionId || "");
  155. }
  156. function windowIdAttributeName(sessionId) {
  157. return WIN_ID_ATTRIBUTE_NAME + (sessionId || "");
  158. }
  159. function inputValueAttributeName(sessionId) {
  160. return INPUT_VALUE_ATTRIBUTE_NAME + (sessionId || "");
  161. }
  162. function sheetAttributeName(sessionId) {
  163. return SHEET_ATTRIBUTE_NAME + (sessionId || "");
  164. }
  165. function getCanvasData(doc) {
  166. if (doc) {
  167. const canvasData = [];
  168. doc.querySelectorAll("canvas").forEach(canvasElement => {
  169. try {
  170. const size = getSize(canvasElement);
  171. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: size.width, height: size.height });
  172. } catch (error) {
  173. canvasData.push(null);
  174. }
  175. });
  176. return canvasData;
  177. }
  178. }
  179. function getStylesheetContents(doc) {
  180. if (doc) {
  181. const contents = [];
  182. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  183. let stylesheet;
  184. try {
  185. const tempStyleElement = doc.createElement("style");
  186. tempStyleElement.textContent = styleElement.textContent;
  187. doc.body.appendChild(tempStyleElement);
  188. stylesheet = tempStyleElement.sheet;
  189. tempStyleElement.remove();
  190. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  191. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n");
  192. }
  193. } catch (error) {
  194. /* ignored */
  195. }
  196. });
  197. return contents;
  198. }
  199. }
  200. function getImageData(doc, options) {
  201. if (doc) {
  202. const data = [];
  203. doc.querySelectorAll("img[src]").forEach((imageElement, imageElementIndex) => {
  204. const computedStyle = getComputedStyle(imageElement);
  205. let imageData = {}, size = getSize(imageElement);
  206. if (imageElement.src && size && (!computedStyle.getPropertyValue("background-image") || computedStyle.getPropertyValue("background-image") == "none")) {
  207. imageElement.setAttribute(imagesAttributeName(options.sessionId), imageElementIndex);
  208. imageData = size;
  209. }
  210. data.push(imageData);
  211. });
  212. return data;
  213. }
  214. }
  215. function getSize(imageElement) {
  216. const computedStyle = getComputedStyle(imageElement);
  217. const paddingLeft = getWidth("padding-left", computedStyle);
  218. const paddingRight = getWidth("padding-right", computedStyle);
  219. const paddingTop = getWidth("padding-top", computedStyle);
  220. const paddingBottom = getWidth("padding-bottom", computedStyle);
  221. const width = imageElement.clientWidth;
  222. const height = imageElement.clientHeight;
  223. if (width >= 0 && height >= 0 && paddingLeft >= 0 && paddingRight >= 0 && paddingTop >= 0 && paddingBottom >= 0) {
  224. return {
  225. width: (paddingLeft || paddingRight) && (width - paddingLeft - paddingRight) + "px",
  226. pxWidth: Math.round(width - paddingLeft - paddingRight),
  227. height: (paddingLeft || paddingRight) && (height - paddingTop - paddingBottom) + "px",
  228. pxHeight: Math.round(height - paddingTop - paddingBottom),
  229. };
  230. }
  231. }
  232. function getWidth(styleName, computedStyle) {
  233. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  234. return parseFloat(computedStyle.getPropertyValue(styleName));
  235. }
  236. }
  237. function getResponsiveImageData(doc, options) {
  238. if (doc) {
  239. const data = [];
  240. doc.querySelectorAll("picture, img[srcset]").forEach((element, elementIndex) => {
  241. const tagName = element.tagName.toLowerCase();
  242. let imageData = {}, imageElement;
  243. element.setAttribute(responsiveImagesAttributeName(options.sessionId), elementIndex);
  244. if (tagName == "picture") {
  245. const sources = Array.from(element.querySelectorAll("source")).map(sourceElement => (
  246. { src: sourceElement.src, srcset: sourceElement.srcset }
  247. ));
  248. imageElement = element.querySelector("img");
  249. imageData.sources = sources;
  250. }
  251. if (tagName == "img") {
  252. imageElement = element;
  253. }
  254. if (imageElement) {
  255. let naturalWidth = imageElement.naturalWidth;
  256. let naturalHeight = imageElement.naturalHeight;
  257. if (naturalWidth <= 1 && naturalHeight <= 1) {
  258. const imgElement = doc.createElement("img");
  259. imgElement.src = imageElement.src;
  260. doc.body.appendChild(imgElement);
  261. naturalWidth = imgElement.width;
  262. naturalHeight = imgElement.height;
  263. imgElement.remove();
  264. }
  265. imageData.source = {
  266. clientWidth: imageElement.clientWidth,
  267. clientHeight: imageElement.clientHeight,
  268. naturalWidth: naturalWidth,
  269. naturalHeight: naturalHeight,
  270. width: imageElement.width,
  271. height: imageElement.height,
  272. src: (!imageElement.currentSrc.startsWith("data:") && imageElement.currentSrc) || (!imageElement.src.startsWith("data:") && imageElement.src)
  273. };
  274. }
  275. data.push(imageData);
  276. });
  277. return data;
  278. }
  279. }
  280. function getPostersData(doc) {
  281. if (doc) {
  282. const postersData = [];
  283. doc.querySelectorAll("video").forEach(videoElement => {
  284. if (videoElement.poster) {
  285. postersData.push(null);
  286. } else {
  287. const canvasElement = doc.createElement("canvas");
  288. const context = canvasElement.getContext("2d");
  289. canvasElement.width = videoElement.clientWidth;
  290. canvasElement.height = videoElement.clientHeight;
  291. try {
  292. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  293. postersData.push(canvasElement.toDataURL("image/png", ""));
  294. } catch (error) {
  295. postersData.push(null);
  296. }
  297. }
  298. });
  299. return postersData;
  300. }
  301. }
  302. function getFontsData() {
  303. if (typeof fontFaceProxy != "undefined") {
  304. return fontFaceProxy.getFontsData();
  305. }
  306. }
  307. function retrieveInputValues(doc, options) {
  308. doc.querySelectorAll("input").forEach(input => input.setAttribute(inputValueAttributeName(options.sessionId), input.value));
  309. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(inputValueAttributeName(options.sessionId), textarea.value));
  310. doc.querySelectorAll("select").forEach(select => {
  311. select.querySelectorAll("option").forEach(option => {
  312. if (option.selected) {
  313. option.setAttribute(inputValueAttributeName(options.sessionId), "");
  314. }
  315. });
  316. });
  317. }
  318. function serialize(doc) {
  319. const docType = doc.doctype;
  320. let docTypeString = "";
  321. if (docType) {
  322. docTypeString = "<!DOCTYPE " + docType.nodeName;
  323. if (docType.publicId) {
  324. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  325. if (docType.systemId) {
  326. docTypeString += " \"" + docType.systemId + "\"";
  327. }
  328. } else if (docType.systemId) {
  329. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  330. } if (docType.internalSubset) {
  331. docTypeString += " [" + docType.internalSubset + "]";
  332. }
  333. docTypeString += "> ";
  334. }
  335. return docTypeString + doc.documentElement.outerHTML;
  336. }
  337. })();