doc-helper.js 15 KB

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