doc-helper.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. };
  69. }
  70. function postProcessDoc(doc, options) {
  71. doc.querySelectorAll("disabled-noscript").forEach(element => {
  72. const noscriptElement = doc.createElement("noscript");
  73. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  74. element.parentElement.replaceChild(noscriptElement, element);
  75. });
  76. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  77. if (options.removeHiddenElements) {
  78. doc.querySelectorAll("[" + removedContentAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(removedContentAttributeName(options.sessionId)));
  79. }
  80. if (options.compressHTML) {
  81. doc.querySelectorAll("[" + preservedSpaceAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(preservedSpaceAttributeName(options.sessionId)));
  82. }
  83. doc.querySelectorAll("[" + responsiveImagesAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(responsiveImagesAttributeName(options.sessionId)));
  84. doc.querySelectorAll("[" + inputValueAttributeName(options.sessionId) + "]").forEach(element => element.removeAttribute(inputValueAttributeName(options.sessionId)));
  85. }
  86. function responsiveImagesAttributeName(sessionId) {
  87. return RESPONSIVE_IMAGE_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  88. }
  89. function preservedSpaceAttributeName(sessionId) {
  90. return PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  91. }
  92. function removedContentAttributeName(sessionId) {
  93. return REMOVED_CONTENT_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  94. }
  95. function windowIdAttributeName(sessionId) {
  96. return WIN_ID_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  97. }
  98. function inputValueAttributeName(sessionId) {
  99. return INPUT_VALUE_ATTRIBUTE_NAME + (sessionId ? "-" + sessionId : "");
  100. }
  101. function getCanvasData(doc) {
  102. if (doc) {
  103. const canvasData = [];
  104. doc.querySelectorAll("canvas").forEach(canvasElement => {
  105. try {
  106. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: canvasElement.clientWidth, height: canvasElement.clientHeight });
  107. } catch (error) {
  108. canvasData.push(null);
  109. }
  110. });
  111. return canvasData;
  112. }
  113. }
  114. function getStylesheetContents(doc) {
  115. if (doc) {
  116. const contents = [];
  117. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  118. let stylesheet;
  119. try {
  120. const tempStyleElement = doc.createElement("style");
  121. tempStyleElement.textContent = styleElement.textContent;
  122. doc.body.appendChild(tempStyleElement);
  123. stylesheet = tempStyleElement.sheet;
  124. tempStyleElement.remove();
  125. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  126. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n");
  127. }
  128. } catch (error) {
  129. /* ignored */
  130. }
  131. });
  132. return contents;
  133. }
  134. }
  135. function getImageData(doc, options) {
  136. if (doc) {
  137. const data = [];
  138. doc.querySelectorAll("picture, img[srcset]").forEach((element, elementIndex) => {
  139. const tagName = element.tagName.toLowerCase();
  140. let imageData = {}, imageElement;
  141. element.setAttribute(responsiveImagesAttributeName(options.sessionId), elementIndex);
  142. if (tagName == "picture") {
  143. const sources = Array.from(element.querySelectorAll("source")).map(sourceElement => (
  144. { src: sourceElement.src, srcset: sourceElement.srcset }
  145. ));
  146. imageElement = element.querySelector("img");
  147. imageData.sources = sources;
  148. }
  149. if (tagName == "img") {
  150. imageElement = element;
  151. }
  152. if (imageElement) {
  153. imageData.source = {
  154. clientWidth: imageElement.clientWidth,
  155. clientHeight: imageElement.clientHeight,
  156. naturalWidth: imageElement.naturalWidth,
  157. naturalHeight: imageElement.naturalHeight,
  158. width: imageElement.width,
  159. height: imageElement.height,
  160. src: (!imageElement.currentSrc.startsWith("data:") && imageElement.currentSrc) || (!imageElement.src.startsWith("data:") && imageElement.src)
  161. };
  162. }
  163. data.push(imageData);
  164. });
  165. return data;
  166. }
  167. }
  168. function getFontsData() {
  169. return fontFaceProxy.getFontsData();
  170. }
  171. function retrieveInputValues(doc, options) {
  172. doc.querySelectorAll("input").forEach(input => input.setAttribute(inputValueAttributeName(options.sessionId), input.value));
  173. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(inputValueAttributeName(options.sessionId), textarea.value));
  174. doc.querySelectorAll("select").forEach(select => {
  175. select.querySelectorAll("option").forEach(option => {
  176. if (option.selected) {
  177. option.setAttribute(inputValueAttributeName(options.sessionId), "");
  178. }
  179. });
  180. });
  181. }
  182. function serialize(doc) {
  183. const docType = doc.doctype;
  184. let docTypeString = "";
  185. if (docType) {
  186. docTypeString = "<!DOCTYPE " + docType.nodeName;
  187. if (docType.publicId) {
  188. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  189. if (docType.systemId) {
  190. docTypeString += " \"" + docType.systemId + "\"";
  191. }
  192. } else if (docType.systemId) {
  193. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  194. } if (docType.internalSubset) {
  195. docTypeString += " [" + docType.internalSubset + "]";
  196. }
  197. docTypeString += "> ";
  198. }
  199. return docTypeString + doc.documentElement.outerHTML;
  200. }
  201. })();