doc-helper.js 8.4 KB

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