doc-helper.js 15 KB

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