single-file-helper.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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-single-file-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-input-value";
  33. const LAZY_SRC_ATTRIBUTE_NAME = "data-single-file-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. LAZY_SRC_ATTRIBUTE_NAME
  56. };
  57. function initDoc(doc) {
  58. doc.querySelectorAll("meta[http-equiv=refresh]").forEach(element => {
  59. element.removeAttribute("http-equiv");
  60. element.setAttribute("disabled-http-equiv", "refresh");
  61. });
  62. }
  63. function preProcessDoc(doc, win, options) {
  64. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  65. doc.querySelectorAll("noscript").forEach(element => {
  66. const disabledNoscriptElement = doc.createElement("disabled-noscript");
  67. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  68. disabledNoscriptElement.hidden = true;
  69. element.parentElement.replaceChild(disabledNoscriptElement, element);
  70. });
  71. initDoc(doc);
  72. if (doc.head) {
  73. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  74. }
  75. let elementsInfo;
  76. if (win && doc.body) {
  77. elementsInfo = getElementsInfo(win, doc, doc.body, options);
  78. } else {
  79. elementsInfo = {
  80. canvases: [],
  81. images: [],
  82. posters: [],
  83. usedFonts: [],
  84. shadowRoots: []
  85. };
  86. }
  87. saveInputValues(doc);
  88. return {
  89. canvases: elementsInfo.canvases,
  90. fonts: getFontsData(doc),
  91. stylesheets: getStylesheetsData(doc),
  92. images: elementsInfo.images,
  93. posters: elementsInfo.posters,
  94. usedFonts: Array.from(elementsInfo.usedFonts),
  95. shadowRoots: elementsInfo.shadowRoots,
  96. referrer: doc.referrer
  97. };
  98. }
  99. function getElementsInfo(win, doc, element, options, data = { usedFonts: new Set(), canvases: [], images: [], posters: [], shadowRoots: [] }, ascendantHidden) {
  100. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  101. elements.forEach(element => {
  102. let elementHidden, computedStyle;
  103. if (options.removeHiddenElements || options.removeUnusedFonts || options.compressHTML) {
  104. computedStyle = win.getComputedStyle(element);
  105. if (options.removeHiddenElements) {
  106. if (ascendantHidden) {
  107. Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement).forEach(element => {
  108. if (!IGNORED_REMOVED_TAG_NAMES.includes(element.tagName)) {
  109. element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
  110. }
  111. });
  112. }
  113. elementHidden = ascendantHidden || testHiddenElement(element, computedStyle);
  114. }
  115. if (!elementHidden) {
  116. if (options.compressHTML) {
  117. const whiteSpace = computedStyle.getPropertyValue("white-space");
  118. if (whiteSpace.startsWith("pre")) {
  119. element.setAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, "");
  120. }
  121. }
  122. if (options.removeUnusedFonts) {
  123. getUsedFont(computedStyle, options, data.usedFonts);
  124. getUsedFont(win.getComputedStyle(element, ":first-letter"), options, data.usedFonts);
  125. getUsedFont(win.getComputedStyle(element, ":before"), options, data.usedFonts);
  126. getUsedFont(win.getComputedStyle(element, ":after"), options, data.usedFonts);
  127. }
  128. }
  129. }
  130. getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle);
  131. if (element.shadowRoot) {
  132. const shadowRootInfo = {};
  133. element.setAttribute(SHADOW_ROOT_ATTRIBUTE_NAME, data.shadowRoots.length);
  134. data.shadowRoots.push(shadowRootInfo);
  135. getElementsInfo(win, doc, element.shadowRoot, options, data, elementHidden);
  136. shadowRootInfo.content = element.shadowRoot.innerHTML;
  137. }
  138. getElementsInfo(win, doc, element, options, data, elementHidden);
  139. });
  140. return data;
  141. }
  142. function getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle) {
  143. if (element.tagName == "CANVAS") {
  144. try {
  145. const size = getSize(win, element, computedStyle);
  146. data.canvases.push({ dataURI: element.toDataURL("image/png", ""), width: size.width, height: size.height });
  147. element.setAttribute(CANVAS_ATTRIBUTE_NAME, data.canvases.length - 1);
  148. } catch (error) {
  149. // ignored
  150. }
  151. }
  152. if (element.tagName == "IMG") {
  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. data.images.push(imageData);
  159. element.setAttribute(IMAGE_ATTRIBUTE_NAME, data.images.length - 1);
  160. element.removeAttribute(LAZY_SRC_ATTRIBUTE_NAME);
  161. computedStyle = computedStyle || win.getComputedStyle(element);
  162. if (computedStyle) {
  163. imageData.size = getSize(win, element, computedStyle);
  164. const boxShadow = computedStyle.getPropertyValue("box-shadow");
  165. const backgroundImage = computedStyle.getPropertyValue("background-image");
  166. if ((!boxShadow || boxShadow == "none") &&
  167. (!backgroundImage || backgroundImage == "none") &&
  168. (imageData.size.pxWidth > 1 || imageData.size.pxHeight > 1)) {
  169. imageData.replaceable = true;
  170. imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
  171. imageData.objectFit = computedStyle.getPropertyValue("object-fit");
  172. imageData.boxSizing = computedStyle.getPropertyValue("box-sizing");
  173. imageData.objectPosition = computedStyle.getPropertyValue("object-position");
  174. }
  175. }
  176. }
  177. if (element.tagName == "VIDEO") {
  178. if (!element.poster) {
  179. const canvasElement = doc.createElement("canvas");
  180. const context = canvasElement.getContext("2d");
  181. canvasElement.width = element.clientWidth;
  182. canvasElement.height = element.clientHeight;
  183. try {
  184. context.drawImage(element, 0, 0, canvasElement.width, canvasElement.height);
  185. data.posters.push(canvasElement.toDataURL("image/png", ""));
  186. element.setAttribute(POSTER_ATTRIBUTE_NAME, data.posters.length - 1);
  187. } catch (error) {
  188. // ignored
  189. }
  190. }
  191. }
  192. if (element.tagName == "IFRAME") {
  193. if (elementHidden) {
  194. element.setAttribute("src", "data:text/html,");
  195. }
  196. }
  197. }
  198. function getUsedFont(computedStyle, options, usedFonts) {
  199. const fontStyle = computedStyle.getPropertyValue("font-style") || "normal";
  200. computedStyle.getPropertyValue("font-family").split(",").forEach(fontFamilyName => {
  201. fontFamilyName = normalizeFontFamily(fontFamilyName);
  202. if (!options.loadedFonts || options.loadedFonts.find(font => normalizeFontFamily(font.family) == fontFamilyName && font.style == fontStyle)) {
  203. const fontWeight = getFontWeight(computedStyle.getPropertyValue("font-weight"));
  204. const fontVariant = computedStyle.getPropertyValue("font-variant") || "normal";
  205. usedFonts.add([fontFamilyName, fontWeight, fontStyle, fontVariant]);
  206. }
  207. });
  208. }
  209. function normalizeFontFamily(fontFamilyName) {
  210. return removeQuotes(fontFamilyName.trim()).toLowerCase();
  211. }
  212. function testHiddenElement(element, computedStyle) {
  213. let hidden = false;
  214. if (computedStyle) {
  215. const display = computedStyle.getPropertyValue("display");
  216. const opacity = computedStyle.getPropertyValue("opacity");
  217. const visibility = computedStyle.getPropertyValue("visibility");
  218. hidden = display == "none";
  219. if (!hidden && (opacity == "0" || visibility == "hidden") && element.getBoundingClientRect) {
  220. const boundingRect = element.getBoundingClientRect();
  221. hidden = !boundingRect.width && !boundingRect.height;
  222. }
  223. }
  224. return Boolean(hidden);
  225. }
  226. function postProcessDoc(doc, options) {
  227. doc.querySelectorAll("disabled-noscript").forEach(element => {
  228. const noscriptElement = doc.createElement("noscript");
  229. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  230. element.parentElement.replaceChild(noscriptElement, element);
  231. });
  232. doc.querySelectorAll("meta[disabled-http-equiv]").forEach(element => {
  233. element.setAttribute("http-equiv", element.getAttribute("disabled-http-equiv"));
  234. element.removeAttribute("disabled-http-equiv");
  235. });
  236. if (doc.head) {
  237. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  238. }
  239. if (options.removeHiddenElements) {
  240. doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  241. }
  242. if (options.compressHTML) {
  243. doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  244. }
  245. doc.querySelectorAll("[" + IMAGE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(IMAGE_ATTRIBUTE_NAME));
  246. doc.querySelectorAll("[" + POSTER_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(POSTER_ATTRIBUTE_NAME));
  247. doc.querySelectorAll("[" + CANVAS_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(CANVAS_ATTRIBUTE_NAME));
  248. doc.querySelectorAll("[" + INPUT_VALUE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(INPUT_VALUE_ATTRIBUTE_NAME));
  249. doc.querySelectorAll("[" + SHADOW_ROOT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(SHADOW_ROOT_ATTRIBUTE_NAME));
  250. }
  251. function getStylesheetsData(doc) {
  252. if (doc) {
  253. const contents = [];
  254. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  255. let stylesheet;
  256. try {
  257. const tempStyleElement = doc.createElement("style");
  258. tempStyleElement.textContent = styleElement.textContent;
  259. doc.body.appendChild(tempStyleElement);
  260. stylesheet = tempStyleElement.sheet;
  261. tempStyleElement.remove();
  262. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  263. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(cssRule => cssRule.cssText).join("\n");
  264. }
  265. } catch (error) {
  266. /* ignored */
  267. }
  268. });
  269. return contents;
  270. }
  271. }
  272. function getSize(win, imageElement, computedStyle) {
  273. let pxWidth = imageElement.naturalWidth;
  274. let pxHeight = imageElement.naturalHeight;
  275. if (!pxWidth && !pxHeight) {
  276. computedStyle = computedStyle || win.getComputedStyle(imageElement);
  277. let removeBorderWidth = false;
  278. if (computedStyle.getPropertyValue("box-sizing") == "content-box") {
  279. const boxSizingValue = imageElement.style.getPropertyValue("box-sizing");
  280. const boxSizingPriority = imageElement.style.getPropertyPriority("box-sizing");
  281. const clientWidth = imageElement.clientWidth;
  282. imageElement.style.setProperty("box-sizing", "border-box", "important");
  283. removeBorderWidth = imageElement.clientWidth != clientWidth;
  284. if (boxSizingValue) {
  285. imageElement.style.setProperty("box-sizing", boxSizingValue, boxSizingPriority);
  286. } else {
  287. imageElement.style.removeProperty("box-sizing");
  288. }
  289. }
  290. let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
  291. paddingLeft = getWidth("padding-left", computedStyle);
  292. paddingRight = getWidth("padding-right", computedStyle);
  293. paddingTop = getWidth("padding-top", computedStyle);
  294. paddingBottom = getWidth("padding-bottom", computedStyle);
  295. if (removeBorderWidth) {
  296. borderLeft = getWidth("border-left-width", computedStyle);
  297. borderRight = getWidth("border-right-width", computedStyle);
  298. borderTop = getWidth("border-top-width", computedStyle);
  299. borderBottom = getWidth("border-bottom-width", computedStyle);
  300. } else {
  301. borderLeft = borderRight = borderTop = borderBottom = 0;
  302. }
  303. pxWidth = Math.max(0, imageElement.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight);
  304. pxHeight = Math.max(0, imageElement.clientHeight - paddingTop - paddingBottom - borderTop - borderBottom);
  305. }
  306. return { pxWidth, pxHeight };
  307. }
  308. function getWidth(styleName, computedStyle) {
  309. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  310. return parseFloat(computedStyle.getPropertyValue(styleName));
  311. }
  312. }
  313. function getFontsData() {
  314. if (singlefile.lib.hooks.content.frames) {
  315. return singlefile.lib.hooks.content.frames.getFontsData();
  316. }
  317. }
  318. function saveInputValues(doc) {
  319. doc.querySelectorAll("input").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.value));
  320. doc.querySelectorAll("input[type=radio], input[type=checkbox]").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.checked));
  321. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, textarea.value));
  322. doc.querySelectorAll("select").forEach(select => {
  323. select.querySelectorAll("option").forEach(option => {
  324. if (option.selected) {
  325. option.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, "");
  326. }
  327. });
  328. });
  329. }
  330. function serialize(doc) {
  331. const docType = doc.doctype;
  332. let docTypeString = "";
  333. if (docType) {
  334. docTypeString = "<!DOCTYPE " + docType.nodeName;
  335. if (docType.publicId) {
  336. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  337. if (docType.systemId) {
  338. docTypeString += " \"" + docType.systemId + "\"";
  339. }
  340. } else if (docType.systemId) {
  341. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  342. } if (docType.internalSubset) {
  343. docTypeString += " [" + docType.internalSubset + "]";
  344. }
  345. docTypeString += "> ";
  346. }
  347. return docTypeString + doc.documentElement.outerHTML;
  348. }
  349. function removeQuotes(string) {
  350. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  351. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  352. } else {
  353. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  354. }
  355. return string.trim();
  356. }
  357. function getFontWeight(weight) {
  358. return FONT_WEIGHTS[weight] || weight;
  359. }
  360. })();