single-file-helper.js 18 KB

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