doc-helper.js 12 KB

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