doc-helper.js 11 KB

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