doc-helper.js 17 KB

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