doc-helper.js 17 KB

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