doc-helper.js 9.3 KB

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