doc-helper.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. imageData = {
  151. width: imageElement.width,
  152. height: imageElement.height,
  153. clientWidth: imageElement.clientWidth,
  154. clientHeight: imageElement.clientHeight,
  155. naturalWidth: imageElement.naturalWidth,
  156. naturalHeight: imageElement.naturalHeight
  157. };
  158. }
  159. data.push(imageData);
  160. });
  161. return data;
  162. }
  163. }
  164. function getResponsiveImageData(doc, options) {
  165. if (doc) {
  166. const data = [];
  167. doc.querySelectorAll("picture, img[srcset]").forEach((element, elementIndex) => {
  168. const tagName = element.tagName.toLowerCase();
  169. let imageData = {}, imageElement;
  170. element.setAttribute(responsiveImagesAttributeName(options.sessionId), elementIndex);
  171. if (tagName == "picture") {
  172. const sources = Array.from(element.querySelectorAll("source")).map(sourceElement => (
  173. { src: sourceElement.src, srcset: sourceElement.srcset }
  174. ));
  175. imageElement = element.querySelector("img");
  176. imageData.sources = sources;
  177. }
  178. if (tagName == "img") {
  179. imageElement = element;
  180. }
  181. if (imageElement) {
  182. imageData.source = {
  183. clientWidth: imageElement.clientWidth,
  184. clientHeight: imageElement.clientHeight,
  185. naturalWidth: imageElement.naturalWidth,
  186. naturalHeight: imageElement.naturalHeight,
  187. width: imageElement.width,
  188. height: imageElement.height,
  189. src: (!imageElement.currentSrc.startsWith("data:") && imageElement.currentSrc) || (!imageElement.src.startsWith("data:") && imageElement.src)
  190. };
  191. }
  192. data.push(imageData);
  193. });
  194. return data;
  195. }
  196. }
  197. function getPostersData(doc) {
  198. if (doc) {
  199. const postersData = [];
  200. doc.querySelectorAll("video").forEach(videoElement => {
  201. if (videoElement.poster) {
  202. postersData.push(null);
  203. } else {
  204. const canvasElement = doc.createElement("canvas");
  205. const context = canvasElement.getContext("2d");
  206. canvasElement.width = videoElement.clientWidth;
  207. canvasElement.height = videoElement.clientHeight;
  208. try {
  209. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  210. postersData.push(canvasElement.toDataURL("image/png", ""));
  211. } catch (error) {
  212. postersData.push(null);
  213. }
  214. }
  215. });
  216. return postersData;
  217. }
  218. }
  219. function getFontsData() {
  220. if (typeof fontFaceProxy != "undefined") {
  221. return fontFaceProxy.getFontsData();
  222. }
  223. }
  224. function retrieveInputValues(doc, options) {
  225. doc.querySelectorAll("input").forEach(input => input.setAttribute(inputValueAttributeName(options.sessionId), input.value));
  226. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(inputValueAttributeName(options.sessionId), textarea.value));
  227. doc.querySelectorAll("select").forEach(select => {
  228. select.querySelectorAll("option").forEach(option => {
  229. if (option.selected) {
  230. option.setAttribute(inputValueAttributeName(options.sessionId), "");
  231. }
  232. });
  233. });
  234. }
  235. function serialize(doc) {
  236. const docType = doc.doctype;
  237. let docTypeString = "";
  238. if (docType) {
  239. docTypeString = "<!DOCTYPE " + docType.nodeName;
  240. if (docType.publicId) {
  241. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  242. if (docType.systemId) {
  243. docTypeString += " \"" + docType.systemId + "\"";
  244. }
  245. } else if (docType.systemId) {
  246. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  247. } if (docType.internalSubset) {
  248. docTypeString += " [" + docType.internalSubset + "]";
  249. }
  250. docTypeString += "> ";
  251. }
  252. return docTypeString + doc.documentElement.outerHTML;
  253. }
  254. })();