single-file-helper.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. this.singlefile.lib.helper = this.singlefile.lib.helper || (() => {
  24. const singlefile = this.singlefile;
  25. const REMOVED_CONTENT_ATTRIBUTE_NAME = "data-single-file-removed-content";
  26. const PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME = "data-single-file-preserved-space-element";
  27. const SHADOW_ROOT_ATTRIBUTE_NAME = "data-single-file-shadow-root-element";
  28. const WIN_ID_ATTRIBUTE_NAME = "data-frame-tree-win-id";
  29. const IMAGE_ATTRIBUTE_NAME = "data-single-file-image";
  30. const POSTER_ATTRIBUTE_NAME = "data-single-file-poster";
  31. const CANVAS_ATTRIBUTE_NAME = "data-single-file-canvas";
  32. const INPUT_VALUE_ATTRIBUTE_NAME = "data-single-file-value";
  33. const LAZY_SRC_ATTRIBUTE_NAME = "data-lazy-loaded-src";
  34. const IGNORED_REMOVED_TAG_NAMES = ["NOSCRIPT", "DISABLED-NOSCRIPT", "META", "LINK", "STYLE", "TITLE", "TEMPLATE", "SOURCE", "OBJECT", "SCRIPT"];
  35. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  36. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  37. const FONT_WEIGHTS = {
  38. normal: "400",
  39. bold: "700"
  40. };
  41. return {
  42. initDoc,
  43. preProcessDoc,
  44. postProcessDoc,
  45. serialize,
  46. removeQuotes,
  47. WIN_ID_ATTRIBUTE_NAME,
  48. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  49. REMOVED_CONTENT_ATTRIBUTE_NAME,
  50. IMAGE_ATTRIBUTE_NAME,
  51. POSTER_ATTRIBUTE_NAME,
  52. CANVAS_ATTRIBUTE_NAME,
  53. INPUT_VALUE_ATTRIBUTE_NAME,
  54. SHADOW_ROOT_ATTRIBUTE_NAME
  55. };
  56. function initDoc(doc) {
  57. doc.querySelectorAll("meta[http-equiv=refresh]").forEach(element => {
  58. element.removeAttribute("http-equiv");
  59. element.setAttribute("disabled-http-equiv", "refresh");
  60. });
  61. }
  62. function preProcessDoc(doc, win, options) {
  63. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  64. doc.querySelectorAll("noscript").forEach(element => {
  65. const disabledNoscriptElement = doc.createElement("disabled-noscript");
  66. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  67. disabledNoscriptElement.hidden = true;
  68. element.parentElement.replaceChild(disabledNoscriptElement, element);
  69. });
  70. initDoc(doc);
  71. if (doc.head) {
  72. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  73. }
  74. let elementsInfo;
  75. if (win && doc.body) {
  76. elementsInfo = getElementsInfo(win, doc, doc.body, options);
  77. } else {
  78. elementsInfo = {
  79. canvases: [],
  80. images: [],
  81. posters: [],
  82. usedFonts: [],
  83. shadowRoots: []
  84. };
  85. }
  86. saveInputValues(doc);
  87. return {
  88. canvases: elementsInfo.canvases,
  89. fonts: getFontsData(doc),
  90. stylesheets: getStylesheetsData(doc),
  91. images: elementsInfo.images,
  92. posters: elementsInfo.posters,
  93. usedFonts: Array.from(elementsInfo.usedFonts),
  94. shadowRoots: elementsInfo.shadowRoots,
  95. referrer: doc.referrer
  96. };
  97. }
  98. function getElementsInfo(win, doc, element, options, data = { usedFonts: new Set(), canvases: [], images: [], posters: [], shadowRoots: [] }, ascendantHidden) {
  99. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  100. elements.forEach(element => {
  101. let elementHidden, computedStyle;
  102. if (options.removeHiddenElements || options.removeUnusedFonts || options.compressHTML) {
  103. computedStyle = win.getComputedStyle(element);
  104. if (options.removeHiddenElements) {
  105. if (ascendantHidden) {
  106. Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement).forEach(element => {
  107. if (!IGNORED_REMOVED_TAG_NAMES.includes(element.tagName)) {
  108. element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
  109. }
  110. });
  111. }
  112. elementHidden = ascendantHidden || testHiddenElement(element, computedStyle);
  113. }
  114. if (!elementHidden) {
  115. if (options.compressHTML) {
  116. const whiteSpace = computedStyle.getPropertyValue("white-space");
  117. if (whiteSpace.startsWith("pre")) {
  118. element.setAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, "");
  119. }
  120. }
  121. if (options.removeUnusedFonts) {
  122. getUsedFont(computedStyle, options, data.usedFonts);
  123. getUsedFont(win.getComputedStyle(element, ":first-letter"), options, data.usedFonts);
  124. getUsedFont(win.getComputedStyle(element, ":before"), options, data.usedFonts);
  125. getUsedFont(win.getComputedStyle(element, ":after"), options, data.usedFonts);
  126. }
  127. }
  128. }
  129. getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle);
  130. if (element.shadowRoot) {
  131. const shadowRootInfo = {};
  132. element.setAttribute(SHADOW_ROOT_ATTRIBUTE_NAME, data.shadowRoots.length);
  133. data.shadowRoots.push(shadowRootInfo);
  134. getElementsInfo(win, doc, element.shadowRoot, options, data, elementHidden);
  135. shadowRootInfo.content = element.shadowRoot.innerHTML;
  136. }
  137. getElementsInfo(win, doc, element, options, data, elementHidden);
  138. });
  139. return data;
  140. }
  141. function getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle) {
  142. if (element.tagName == "CANVAS") {
  143. try {
  144. const size = getSize(win, element, computedStyle);
  145. data.canvases.push({ dataURI: element.toDataURL("image/png", ""), width: size.width, height: size.height });
  146. element.setAttribute(CANVAS_ATTRIBUTE_NAME, data.canvases.length - 1);
  147. } catch (error) {
  148. // ignored
  149. }
  150. }
  151. if (element.tagName == "IMG") {
  152. element.setAttribute(IMAGE_ATTRIBUTE_NAME, data.images.length);
  153. const imageData = {
  154. currentSrc: elementHidden ?
  155. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" :
  156. (options.loadDeferredImages && element.getAttribute(LAZY_SRC_ATTRIBUTE_NAME)) || element.currentSrc
  157. };
  158. element.removeAttribute(LAZY_SRC_ATTRIBUTE_NAME);
  159. computedStyle = computedStyle || win.getComputedStyle(element);
  160. if (computedStyle) {
  161. imageData.size = getSize(win, element, computedStyle);
  162. const boxShadow = computedStyle.getPropertyValue("box-shadow");
  163. const backgroundImage = computedStyle.getPropertyValue("background-image");
  164. if ((!boxShadow || boxShadow == "none") &&
  165. (!backgroundImage || backgroundImage == "none") &&
  166. (imageData.size.pxWidth > 1 || imageData.size.pxHeight > 1)) {
  167. imageData.replaceable = true;
  168. imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
  169. imageData.objectFit = computedStyle.getPropertyValue("object-fit");
  170. imageData.boxSizing = computedStyle.getPropertyValue("box-sizing");
  171. imageData.objectPosition = computedStyle.getPropertyValue("object-position");
  172. }
  173. }
  174. data.images.push(imageData);
  175. }
  176. if (element.tagName == "VIDEO") {
  177. if (!element.poster) {
  178. const canvasElement = doc.createElement("canvas");
  179. const context = canvasElement.getContext("2d");
  180. canvasElement.width = element.clientWidth;
  181. canvasElement.height = element.clientHeight;
  182. try {
  183. context.drawImage(element, 0, 0, canvasElement.width, canvasElement.height);
  184. data.posters.push(canvasElement.toDataURL("image/png", ""));
  185. element.setAttribute(POSTER_ATTRIBUTE_NAME, data.posters.length - 1);
  186. } catch (error) {
  187. // ignored
  188. }
  189. }
  190. }
  191. if (element.tagName == "IFRAME") {
  192. if (elementHidden) {
  193. element.setAttribute("src", "data:text/html,");
  194. }
  195. }
  196. }
  197. function getUsedFont(computedStyle, options, usedFonts) {
  198. const fontStyle = computedStyle.getPropertyValue("font-style") || "normal";
  199. computedStyle.getPropertyValue("font-family").split(",").forEach(fontFamilyName => {
  200. fontFamilyName = normalizeFontFamily(fontFamilyName);
  201. if (!options.loadedFonts || options.loadedFonts.find(font => normalizeFontFamily(font.family) == fontFamilyName && font.style == fontStyle)) {
  202. const fontWeight = getFontWeight(computedStyle.getPropertyValue("font-weight"));
  203. const fontVariant = computedStyle.getPropertyValue("font-variant") || "normal";
  204. usedFonts.add([fontFamilyName, fontWeight, fontStyle, fontVariant]);
  205. }
  206. });
  207. }
  208. function normalizeFontFamily(fontFamilyName) {
  209. return removeQuotes(fontFamilyName.trim()).toLowerCase();
  210. }
  211. function testHiddenElement(element, computedStyle) {
  212. let hidden = false;
  213. if (computedStyle) {
  214. const display = computedStyle.getPropertyValue("display");
  215. const opacity = computedStyle.getPropertyValue("opacity");
  216. const visibility = computedStyle.getPropertyValue("visibility");
  217. hidden = display == "none";
  218. if (!hidden && (opacity == "0" || visibility == "hidden") && element.getBoundingClientRect) {
  219. const boundingRect = element.getBoundingClientRect();
  220. hidden = !boundingRect.width && !boundingRect.height;
  221. }
  222. }
  223. return Boolean(hidden);
  224. }
  225. function postProcessDoc(doc, options) {
  226. doc.querySelectorAll("disabled-noscript").forEach(element => {
  227. const noscriptElement = doc.createElement("noscript");
  228. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  229. element.parentElement.replaceChild(noscriptElement, element);
  230. });
  231. doc.querySelectorAll("meta[disabled-http-equiv]").forEach(element => {
  232. element.setAttribute("http-equiv", element.getAttribute("disabled-http-equiv"));
  233. element.removeAttribute("disabled-http-equiv");
  234. });
  235. if (doc.head) {
  236. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  237. }
  238. if (options.removeHiddenElements) {
  239. doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  240. }
  241. if (options.compressHTML) {
  242. doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  243. }
  244. doc.querySelectorAll("[" + IMAGE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(IMAGE_ATTRIBUTE_NAME));
  245. doc.querySelectorAll("[" + POSTER_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(POSTER_ATTRIBUTE_NAME));
  246. doc.querySelectorAll("[" + CANVAS_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(CANVAS_ATTRIBUTE_NAME));
  247. doc.querySelectorAll("[" + INPUT_VALUE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(INPUT_VALUE_ATTRIBUTE_NAME));
  248. doc.querySelectorAll("[" + SHADOW_ROOT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(SHADOW_ROOT_ATTRIBUTE_NAME));
  249. }
  250. function getStylesheetsData(doc) {
  251. if (doc) {
  252. const contents = [];
  253. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  254. let stylesheet;
  255. try {
  256. const tempStyleElement = doc.createElement("style");
  257. tempStyleElement.textContent = styleElement.textContent;
  258. doc.body.appendChild(tempStyleElement);
  259. stylesheet = tempStyleElement.sheet;
  260. tempStyleElement.remove();
  261. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  262. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(cssRule => cssRule.cssText).join("\n");
  263. }
  264. } catch (error) {
  265. /* ignored */
  266. }
  267. });
  268. return contents;
  269. }
  270. }
  271. function getSize(win, imageElement, computedStyle) {
  272. let pxWidth = imageElement.naturalWidth;
  273. let pxHeight = imageElement.naturalHeight;
  274. if (!pxWidth && !pxHeight) {
  275. computedStyle = computedStyle || win.getComputedStyle(imageElement);
  276. let removeBorderWidth = false;
  277. if (computedStyle.getPropertyValue("box-sizing") == "content-box") {
  278. const boxSizingValue = imageElement.style.getPropertyValue("box-sizing");
  279. const boxSizingPriority = imageElement.style.getPropertyPriority("box-sizing");
  280. const clientWidth = imageElement.clientWidth;
  281. imageElement.style.setProperty("box-sizing", "border-box", "important");
  282. removeBorderWidth = imageElement.clientWidth != clientWidth;
  283. if (boxSizingValue) {
  284. imageElement.style.setProperty("box-sizing", boxSizingValue, boxSizingPriority);
  285. } else {
  286. imageElement.style.removeProperty("box-sizing");
  287. }
  288. }
  289. let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
  290. paddingLeft = getWidth("padding-left", computedStyle);
  291. paddingRight = getWidth("padding-right", computedStyle);
  292. paddingTop = getWidth("padding-top", computedStyle);
  293. paddingBottom = getWidth("padding-bottom", computedStyle);
  294. if (removeBorderWidth) {
  295. borderLeft = getWidth("border-left-width", computedStyle);
  296. borderRight = getWidth("border-right-width", computedStyle);
  297. borderTop = getWidth("border-top-width", computedStyle);
  298. borderBottom = getWidth("border-bottom-width", computedStyle);
  299. } else {
  300. borderLeft = borderRight = borderTop = borderBottom = 0;
  301. }
  302. pxWidth = Math.max(0, imageElement.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight);
  303. pxHeight = Math.max(0, imageElement.clientHeight - paddingTop - paddingBottom - borderTop - borderBottom);
  304. }
  305. return { pxWidth, pxHeight };
  306. }
  307. function getWidth(styleName, computedStyle) {
  308. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  309. return parseFloat(computedStyle.getPropertyValue(styleName));
  310. }
  311. }
  312. function getFontsData() {
  313. if (singlefile.lib.hooks.content.frames) {
  314. return singlefile.lib.hooks.content.frames.getFontsData();
  315. }
  316. }
  317. function saveInputValues(doc) {
  318. doc.querySelectorAll("input").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.value));
  319. doc.querySelectorAll("input[type=radio], input[type=checkbox]").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.checked));
  320. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, textarea.value));
  321. doc.querySelectorAll("select").forEach(select => {
  322. select.querySelectorAll("option").forEach(option => {
  323. if (option.selected) {
  324. option.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, "");
  325. }
  326. });
  327. });
  328. }
  329. function serialize(doc) {
  330. const docType = doc.doctype;
  331. let docTypeString = "";
  332. if (docType) {
  333. docTypeString = "<!DOCTYPE " + docType.nodeName;
  334. if (docType.publicId) {
  335. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  336. if (docType.systemId) {
  337. docTypeString += " \"" + docType.systemId + "\"";
  338. }
  339. } else if (docType.systemId) {
  340. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  341. } if (docType.internalSubset) {
  342. docTypeString += " [" + docType.internalSubset + "]";
  343. }
  344. docTypeString += "> ";
  345. }
  346. return docTypeString + doc.documentElement.outerHTML;
  347. }
  348. function removeQuotes(string) {
  349. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  350. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  351. } else {
  352. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  353. }
  354. return string.trim();
  355. }
  356. function getFontWeight(weight) {
  357. return FONT_WEIGHTS[weight] || weight;
  358. }
  359. })();