doc-helper.js 12 KB

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