single-file-helper.js 17 KB

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