single-file-helper.js 18 KB

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