1
0

single-file-helper.js 16 KB

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