doc-helper.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 */
  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. return {
  30. preProcessDoc,
  31. postProcessDoc,
  32. serialize,
  33. windowIdAttributeName,
  34. preservedSpaceAttributeName,
  35. removedContentAttributeName,
  36. responsiveImagesAttributeName,
  37. imagesAttributeName,
  38. inputValueAttributeName,
  39. sheetAttributeName
  40. };
  41. function preProcessDoc(doc, win, options) {
  42. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  43. doc.querySelectorAll("noscript").forEach(element => {
  44. const disabledNoscriptElement = doc.createElement("disabled-noscript");
  45. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  46. disabledNoscriptElement.hidden = true;
  47. element.parentElement.replaceChild(disabledNoscriptElement, element);
  48. });
  49. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  50. if (options.removeHiddenElements) {
  51. doc.querySelectorAll("html > body *:not(style):not(script):not(link):not(frame):not(iframe):not(object):not(meta):not(title):not(meta):not(noscript):not(template)").forEach(element => {
  52. const style = win.getComputedStyle(element);
  53. if (element instanceof win.HTMLElement && style && (element.hidden || style.display == "none" || ((style.opacity === 0 || style.visibility == "hidden") && !element.clientWidth && !element.clientHeight)) && !element.querySelector("iframe, frame, object[type=\"text/html\"][data]")) {
  54. element.setAttribute(removedContentAttributeName(options.sessionId), "");
  55. }
  56. });
  57. }
  58. if (options.compressHTML) {
  59. doc.querySelectorAll("*").forEach(element => {
  60. const style = win.getComputedStyle(element);
  61. if (style && style.whiteSpace.startsWith("pre")) {
  62. element.setAttribute(preservedSpaceAttributeName(options.sessionId), "");
  63. }
  64. });
  65. }
  66. retrieveInputValues(doc, options);
  67. return {
  68. canvasData: getCanvasData(doc),
  69. fontsData: getFontsData(doc),
  70. stylesheetContents: getStylesheetContents(doc),
  71. responsiveImageData: getResponsiveImageData(doc, options),
  72. imageData: getImageData(doc, options),
  73. postersData: getPostersData(doc)
  74. };
  75. }
  76. function postProcessDoc(doc, options) {
  77. doc.querySelectorAll("disabled-noscript").forEach(element => {
  78. const noscriptElement = doc.createElement("noscript");
  79. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  80. element.parentElement.replaceChild(noscriptElement, element);
  81. });
  82. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  83. if (options.removeHiddenElements) {
  84. doc.querySelectorAll("[" + removedContentAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(removedContentAttributeName(options.sessionId)));
  85. }
  86. if (options.compressHTML) {
  87. doc.querySelectorAll("[" + preservedSpaceAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(preservedSpaceAttributeName(options.sessionId)));
  88. }
  89. doc.querySelectorAll("[" + responsiveImagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(responsiveImagesAttributeName(options.sessionId)));
  90. doc.querySelectorAll("[" + imagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(imagesAttributeName(options.sessionId)));
  91. doc.querySelectorAll("[" + inputValueAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(inputValueAttributeName(options.sessionId)));
  92. }
  93. function responsiveImagesAttributeName(sessionId) {
  94. return RESPONSIVE_IMAGE_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  95. }
  96. function imagesAttributeName(sessionId) {
  97. return IMAGE_ATTRIBUTE_NAME + (sessionId || "");
  98. }
  99. function preservedSpaceAttributeName(sessionId) {
  100. return PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + (sessionId || "");
  101. }
  102. function removedContentAttributeName(sessionId) {
  103. return REMOVED_CONTENT_ATTRIBUTE_NAME + (sessionId || "");
  104. }
  105. function windowIdAttributeName(sessionId) {
  106. return WIN_ID_ATTRIBUTE_NAME + (sessionId || "");
  107. }
  108. function inputValueAttributeName(sessionId) {
  109. return INPUT_VALUE_ATTRIBUTE_NAME + (sessionId || "");
  110. }
  111. function sheetAttributeName(sessionId) {
  112. return SHEET_ATTRIBUTE_NAME + (sessionId || "");
  113. }
  114. function getCanvasData(doc) {
  115. if (doc) {
  116. const canvasData = [];
  117. doc.querySelectorAll("canvas").forEach(canvasElement => {
  118. try {
  119. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: canvasElement.clientWidth, height: canvasElement.clientHeight });
  120. } catch (error) {
  121. canvasData.push(null);
  122. }
  123. });
  124. return canvasData;
  125. }
  126. }
  127. function getStylesheetContents(doc) {
  128. if (doc) {
  129. const contents = [];
  130. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  131. let stylesheet;
  132. try {
  133. const tempStyleElement = doc.createElement("style");
  134. tempStyleElement.textContent = styleElement.textContent;
  135. doc.body.appendChild(tempStyleElement);
  136. stylesheet = tempStyleElement.sheet;
  137. tempStyleElement.remove();
  138. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  139. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n");
  140. }
  141. } catch (error) {
  142. /* ignored */
  143. }
  144. });
  145. return contents;
  146. }
  147. }
  148. function getImageData(doc, options) {
  149. if (doc) {
  150. const data = [];
  151. doc.querySelectorAll("img[src]").forEach((imageElement, imageElementIndex) => {
  152. const computedStyle = getComputedStyle(imageElement);
  153. let imageData = {}, size = getSize(imageElement);
  154. if (imageElement.src && size && (!computedStyle.getPropertyValue("background-image") || computedStyle.getPropertyValue("background-image") == "none")) {
  155. imageElement.setAttribute(imagesAttributeName(options.sessionId), imageElementIndex);
  156. imageData = size;
  157. }
  158. data.push(imageData);
  159. });
  160. return data;
  161. }
  162. }
  163. function getSize(imageElement) {
  164. const computedStyle = getComputedStyle(imageElement);
  165. const paddingLeft = getWidth("padding-left", computedStyle);
  166. const paddingRight = getWidth("padding-right", computedStyle);
  167. const paddingTop = getWidth("padding-top", computedStyle);
  168. const paddingBottom = getWidth("padding-bottom", computedStyle);
  169. const width = imageElement.clientWidth;
  170. const height = imageElement.clientHeight;
  171. if (width >= 0 && height >= 0 && paddingLeft >= 0 && paddingRight >= 0 && paddingTop >= 0 && paddingBottom >= 0) {
  172. return {
  173. width: Math.ceil(width - paddingLeft - paddingRight),
  174. height: Math.floor(height - paddingTop - paddingBottom),
  175. };
  176. }
  177. }
  178. function getWidth(styleName, computedStyle) {
  179. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  180. return parseFloat(computedStyle.getPropertyValue(styleName));
  181. }
  182. }
  183. function getResponsiveImageData(doc, options) {
  184. if (doc) {
  185. const data = [];
  186. doc.querySelectorAll("picture, img[srcset]").forEach((element, elementIndex) => {
  187. const tagName = element.tagName.toLowerCase();
  188. let imageData = {}, imageElement;
  189. element.setAttribute(responsiveImagesAttributeName(options.sessionId), elementIndex);
  190. if (tagName == "picture") {
  191. const sources = Array.from(element.querySelectorAll("source")).map(sourceElement => (
  192. { src: sourceElement.src, srcset: sourceElement.srcset }
  193. ));
  194. imageElement = element.querySelector("img");
  195. imageData.sources = sources;
  196. }
  197. if (tagName == "img") {
  198. imageElement = element;
  199. }
  200. if (imageElement) {
  201. let naturalWidth = imageElement.naturalWidth;
  202. let naturalHeight = imageElement.naturalHeight;
  203. if (naturalWidth <= 1 && naturalHeight <= 1) {
  204. const imgElement = doc.createElement("img");
  205. imgElement.src = imageElement.src;
  206. doc.body.appendChild(imgElement);
  207. naturalWidth = imgElement.width;
  208. naturalHeight = imgElement.height;
  209. imgElement.remove();
  210. }
  211. imageData.source = {
  212. clientWidth: imageElement.clientWidth,
  213. clientHeight: imageElement.clientHeight,
  214. naturalWidth: naturalWidth,
  215. naturalHeight: naturalHeight,
  216. width: imageElement.width,
  217. height: imageElement.height,
  218. src: (!imageElement.src.startsWith("data:") && imageElement.src) || (!imageElement.currentSrc.startsWith("data:") && imageElement.currentSrc)
  219. };
  220. }
  221. data.push(imageData);
  222. });
  223. return data;
  224. }
  225. }
  226. function getPostersData(doc) {
  227. if (doc) {
  228. const postersData = [];
  229. doc.querySelectorAll("video").forEach(videoElement => {
  230. if (videoElement.poster) {
  231. postersData.push(null);
  232. } else {
  233. const canvasElement = doc.createElement("canvas");
  234. const context = canvasElement.getContext("2d");
  235. canvasElement.width = videoElement.clientWidth;
  236. canvasElement.height = videoElement.clientHeight;
  237. try {
  238. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  239. postersData.push(canvasElement.toDataURL("image/png", ""));
  240. } catch (error) {
  241. postersData.push(null);
  242. }
  243. }
  244. });
  245. return postersData;
  246. }
  247. }
  248. function getFontsData() {
  249. if (typeof fontFaceProxy != "undefined") {
  250. return fontFaceProxy.getFontsData();
  251. }
  252. }
  253. function retrieveInputValues(doc, options) {
  254. doc.querySelectorAll("input").forEach(input => input.setAttribute(inputValueAttributeName(options.sessionId), input.value));
  255. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(inputValueAttributeName(options.sessionId), textarea.value));
  256. doc.querySelectorAll("select").forEach(select => {
  257. select.querySelectorAll("option").forEach(option => {
  258. if (option.selected) {
  259. option.setAttribute(inputValueAttributeName(options.sessionId), "");
  260. }
  261. });
  262. });
  263. }
  264. function serialize(doc) {
  265. const docType = doc.doctype;
  266. let docTypeString = "";
  267. if (docType) {
  268. docTypeString = "<!DOCTYPE " + docType.nodeName;
  269. if (docType.publicId) {
  270. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  271. if (docType.systemId) {
  272. docTypeString += " \"" + docType.systemId + "\"";
  273. }
  274. } else if (docType.systemId) {
  275. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  276. } if (docType.internalSubset) {
  277. docTypeString += " [" + docType.internalSubset + "]";
  278. }
  279. docTypeString += "> ";
  280. }
  281. return docTypeString + doc.documentElement.outerHTML;
  282. }
  283. })();