doc-helper.js 16 KB

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