single-file-core.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global Blob */
  21. this.SingleFileCore = this.SingleFileCore || (() => {
  22. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  23. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  24. const REMOVED_CONTENT_ATTRIBUTE_NAME = "data-single-file-removed-content";
  25. const PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME = "data-single-file-preserved-space-element";
  26. const WIN_ID_ATTRIBUTE_NAME = "data-frame-tree-win-id";
  27. let Download, DOM, URL;
  28. function getClass(...args) {
  29. [Download, DOM, URL] = args;
  30. return class {
  31. constructor(options) {
  32. this.options = options;
  33. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  34. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  35. }
  36. async initialize() {
  37. this.processor = new PageProcessor(this.options);
  38. await this.processor.loadPage();
  39. await this.processor.initialize();
  40. }
  41. async preparePageData() {
  42. await this.processor.preparePageData();
  43. }
  44. getPageData() {
  45. return this.processor.getPageData();
  46. }
  47. };
  48. }
  49. // -------------
  50. // ProgressEvent
  51. // -------------
  52. const PAGE_LOADING = "page-loading";
  53. const PAGE_LOADED = "page-loaded";
  54. const RESOURCES_INITIALIZING = "resource-initializing";
  55. const RESOURCES_INITIALIZED = "resources-initialized";
  56. const RESOURCE_LOADED = "resource-loaded";
  57. const PAGE_ENDED = "page-ended";
  58. class ProgressEvent {
  59. constructor(type, details) {
  60. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  61. }
  62. }
  63. // -------------
  64. // PageProcessor
  65. // -------------
  66. class PageProcessor {
  67. constructor(options) {
  68. this.options = options;
  69. this.options.url = this.options.url || this.options.doc.location.href;
  70. this.processor = new DOMProcessor(options);
  71. if (this.options.doc) {
  72. this.options.canvasData = this.processor.getCanvasData();
  73. this.options.emptyStyleRulesText = this.processor.getEmptyStyleRulesText();
  74. this.processor.fixInlineScripts();
  75. this.processor.disableNoscriptElements();
  76. this.processor.hideNonMetadataContents();
  77. if (this.options.removeHiddenElements) {
  78. this.processor.markRemovedElements();
  79. }
  80. if (this.options.compressHTML) {
  81. this.processor.markPreservedElements();
  82. }
  83. }
  84. this.options.content = this.options.content || (this.options.doc ? DOMProcessor.serialize(this.options.doc, false) : null);
  85. this.onprogress = options.onprogress || (() => { });
  86. }
  87. async loadPage() {
  88. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  89. await this.processor.loadPage(this.options.content);
  90. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  91. }
  92. async initialize() {
  93. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  94. this.processor.removeInfoToolbar();
  95. this.processor.enableDisabledNoscriptTags(this.processor.doc.head.querySelectorAll("disabled-noscript"));
  96. this.processor.replaceEmptyStyles();
  97. if (!this.options.jsEnabled || (this.options.saveRawPage && this.options.removeScripts)) {
  98. this.processor.insertNoscriptContents();
  99. }
  100. if (this.options.removeFrames) {
  101. this.processor.removeFrames();
  102. }
  103. if (this.options.removeImports) {
  104. this.processor.removeImports();
  105. }
  106. if (this.options.removeScripts) {
  107. this.processor.removeScripts();
  108. }
  109. this.processor.removeDiscardedResources();
  110. this.processor.resetCharsetMeta();
  111. if (this.options.compressHTML) {
  112. this.processor.compressHTML();
  113. }
  114. if (this.options.insertFaviconLink) {
  115. this.processor.insertFaviconLink();
  116. }
  117. this.processor.resolveHrefs();
  118. this.processor.replaceCanvasElements();
  119. if (this.options.removeHiddenElements) {
  120. this.processor.removeHiddenElements();
  121. }
  122. const initializationPromises = [this.processor.inlineStylesheets(true), this.processor.linkStylesheets(), this.processor.attributeStyles(true)];
  123. if (!this.options.removeFrames) {
  124. initializationPromises.push(this.processor.frames(true));
  125. }
  126. if (!this.options.removeImports) {
  127. initializationPromises.push(this.processor.htmlImports(true));
  128. }
  129. await Promise.all(initializationPromises);
  130. if (this.options.compressHTML) {
  131. this.processor.compressHTML();
  132. }
  133. if (this.options.removeUnusedCSSRules) {
  134. this.processor.removeUnusedCSSRules();
  135. }
  136. this.pendingPromises = [this.processor.inlineStylesheets(), this.processor.attributeStyles(), this.processor.pageResources()];
  137. if (!this.options.removeScripts) {
  138. this.pendingPromises.push(this.processor.scripts());
  139. }
  140. if (this.options.doc) {
  141. this.processor.enableDisabledNoscriptTags(this.options.doc.querySelectorAll("disabled-noscript"));
  142. this.processor.displayHiddenNonMetadataContents();
  143. if (this.options.removeHiddenElements) {
  144. this.processor.unmarkRemovedElements();
  145. }
  146. if (this.options.compressHTML) {
  147. this.processor.unmarkPreservedElements();
  148. }
  149. if (!this.options.removeFrames) {
  150. this.processor.removeWindowIdFrames();
  151. }
  152. this.options.doc = null;
  153. this.options.win = null;
  154. }
  155. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  156. }
  157. async preparePageData() {
  158. await this.processor.retrieveResources(
  159. details => {
  160. details.pageURL = this.options.url;
  161. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  162. });
  163. await this.pendingPromises;
  164. if (this.options.lazyLoadImages) {
  165. this.processor.lazyLoadImages();
  166. }
  167. if (!this.options.removeFrames) {
  168. await this.processor.frames();
  169. }
  170. if (!this.options.removeImports) {
  171. await this.processor.htmlImports();
  172. }
  173. if (this.options.compressHTML) {
  174. this.processor.compressHTML(true);
  175. }
  176. if (this.options.insertSingleFileComment) {
  177. this.processor.insertSingleFileCommentNode();
  178. }
  179. this.processor.removeBase();
  180. }
  181. getPageData() {
  182. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  183. return this.processor.getPageData();
  184. }
  185. }
  186. // --------
  187. // BatchRequest
  188. // --------
  189. class BatchRequest {
  190. constructor() {
  191. this.requests = new Map();
  192. }
  193. async addURL(resourceURL) {
  194. return new Promise((resolve, reject) => {
  195. const resourceRequests = this.requests.get(resourceURL);
  196. if (resourceRequests) {
  197. resourceRequests.push({ resolve, reject });
  198. } else {
  199. this.requests.set(resourceURL, [{ resolve, reject }]);
  200. }
  201. });
  202. }
  203. getMaxResources() {
  204. return Array.from(this.requests.keys()).length;
  205. }
  206. async run(onloadListener, options) {
  207. const resourceURLs = Array.from(this.requests.keys());
  208. let indexResource = 0;
  209. return Promise.all(resourceURLs.map(async resourceURL => {
  210. const resourceRequests = this.requests.get(resourceURL);
  211. try {
  212. const dataURI = await Download.getContent(resourceURL, { asDataURI: true, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  213. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  214. } catch (error) {
  215. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  216. }
  217. this.requests.delete(resourceURL);
  218. indexResource = indexResource + 1;
  219. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  220. }));
  221. }
  222. }
  223. // ------------
  224. // DOMProcessor
  225. // ------------
  226. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  227. const EMPTY_DATA_URI = "data:base64,";
  228. const STATS_DEFAULT_VALUES = {
  229. discarded: {
  230. htmlBytes: 0,
  231. hiddenElements: 0,
  232. imports: 0,
  233. scripts: 0,
  234. objects: 0,
  235. audioSource: 0,
  236. videoSource: 0,
  237. frames: 0,
  238. cssRules: 0
  239. },
  240. processed: {
  241. htmlBytes: 0,
  242. imports: 0,
  243. scripts: 0,
  244. frames: 0,
  245. cssRules: 0,
  246. canvas: 0,
  247. styleSheets: 0,
  248. resources: 0
  249. }
  250. };
  251. const batchRequest = new BatchRequest();
  252. class DOMProcessor {
  253. constructor(options) {
  254. this.options = options;
  255. if (this.options.displayStats) {
  256. this.stats = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  257. }
  258. this.baseURI = options.url;
  259. }
  260. static serialize(doc, compressHTML) {
  261. return DOM.serialize(doc, compressHTML);
  262. }
  263. async loadPage(pageContent) {
  264. if (!pageContent || this.options.saveRawPage) {
  265. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  266. }
  267. this.dom = DOM.create(pageContent, this.baseURI);
  268. this.DOMParser = this.dom.DOMParser;
  269. this.doc = this.dom.document;
  270. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  271. await DOMProcessor.loadEscapedFragmentPage();
  272. }
  273. }
  274. async loadEscapedFragmentPage() {
  275. if (this.baseURI.includes("?")) {
  276. this.baseURI += "&";
  277. } else {
  278. this.baseURI += "?";
  279. }
  280. this.baseURI += ESCAPED_FRAGMENT;
  281. await this.loadPage();
  282. }
  283. async retrieveResources(onloadListener) {
  284. if (this.options.displayStats) {
  285. this.stats.processed.resources = batchRequest.getMaxResources();
  286. }
  287. await batchRequest.run(onloadListener, this.options);
  288. }
  289. getPageData() {
  290. if (this.options.selected) {
  291. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  292. if (rootElement) {
  293. DomProcessorHelper.isolateElements(rootElement);
  294. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  295. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  296. }
  297. }
  298. const titleElement = this.doc.querySelector("title");
  299. let title;
  300. if (titleElement) {
  301. title = titleElement.textContent.trim();
  302. }
  303. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  304. let size;
  305. if (this.options.displayStats) {
  306. size = new Blob([this.doc.documentElement.outerHTML]).size;
  307. }
  308. const content = DOMProcessor.serialize(this.doc, this.options.compressHTML);
  309. if (this.options.displayStats) {
  310. this.stats.processed.htmlBytes = new Blob([content]).size;
  311. this.stats.discarded.htmlBytes += size - this.stats.processed.htmlBytes;
  312. }
  313. return {
  314. stats: this.stats,
  315. title: title || (this.baseURI && matchTitle ? matchTitle[1] : ""),
  316. content
  317. };
  318. }
  319. fixInlineScripts() {
  320. this.options.doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  321. }
  322. disableNoscriptElements() {
  323. this.options.doc.head.querySelectorAll("noscript").forEach(element => {
  324. const disabledNoscriptElement = this.options.doc.createElement("disabled-noscript");
  325. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  326. disabledNoscriptElement.hidden = true;
  327. element.parentElement.replaceChild(disabledNoscriptElement, element);
  328. });
  329. }
  330. hideNonMetadataContents() {
  331. this.options.doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  332. }
  333. markRemovedElements() {
  334. this.options.doc.querySelectorAll("html > body *:not(style):not(script):not(link):not(frame):not(iframe):not(object)").forEach(element => {
  335. const style = this.options.win.getComputedStyle(element);
  336. if (element instanceof this.options.win.HTMLElement && (element.hidden || style.display == "none" || ((style.opacity === 0 || style.visibility == "hidden") && !element.clientWidth && !element.clientHeight)) && !element.querySelector("iframe, frame, object[type=\"text/html\"][data]")) {
  337. element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
  338. }
  339. });
  340. }
  341. markPreservedElements() {
  342. this.options.doc.querySelectorAll("*").forEach(element => {
  343. const style = this.options.win.getComputedStyle(element);
  344. if (style.whiteSpace.startsWith("pre")) {
  345. element.setAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, "");
  346. }
  347. });
  348. }
  349. displayHiddenNonMetadataContents() {
  350. this.options.doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  351. }
  352. unmarkPreservedElements() {
  353. this.options.doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  354. }
  355. unmarkRemovedElements() {
  356. this.options.doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  357. }
  358. removeWindowIdFrames() {
  359. this.options.doc.querySelectorAll("[" + WIN_ID_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(WIN_ID_ATTRIBUTE_NAME));
  360. }
  361. getEmptyStyleRulesText() {
  362. const textData = [];
  363. this.options.doc.querySelectorAll("style").forEach(styleElement => {
  364. if (!styleElement.textContent) {
  365. textData.push(Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n"));
  366. }
  367. });
  368. return textData;
  369. }
  370. getCanvasData() {
  371. const canvasData = [];
  372. this.options.doc.querySelectorAll("canvas").forEach(canvasElement => {
  373. try {
  374. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: canvasElement.clientWidth, height: canvasElement.clientHeight });
  375. } catch (error) {
  376. canvasData.push(null);
  377. }
  378. });
  379. return canvasData;
  380. }
  381. enableDisabledNoscriptTags(noscriptTags) {
  382. noscriptTags.forEach(element => {
  383. const noscriptElement = this.options.doc.createElement("noscript");
  384. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  385. element.parentElement.replaceChild(noscriptElement, element);
  386. });
  387. }
  388. insertNoscriptContents() {
  389. if (this.DOMParser) {
  390. this.doc.querySelectorAll("noscript").forEach(element => {
  391. const fragment = this.doc.createDocumentFragment();
  392. Array.from(element.childNodes).forEach(node => {
  393. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  394. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  395. this.doc.importNode(node);
  396. fragment.appendChild(node);
  397. });
  398. });
  399. element.parentElement.replaceChild(fragment, element);
  400. });
  401. }
  402. }
  403. lazyLoadImages() {
  404. this.dom.lazyLoader.process(this.doc);
  405. }
  406. removeDiscardedResources() {
  407. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed:not([src*=\".svg\"]), link[rel*=preload], link[rel*=prefetch]");
  408. if (this.options.displayStats) {
  409. this.stats.discarded.objects = objectElements.length;
  410. }
  411. objectElements.forEach(element => element.remove());
  412. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  413. this.doc.querySelectorAll("[onerror]").forEach(element => element.removeAttribute("onerror"));
  414. if (this.options.removeAudioSrc) {
  415. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  416. if (this.options.displayStats) {
  417. this.stats.discarded.audioSource = objectElements.length;
  418. }
  419. audioSourceElements.forEach(element => element.removeAttribute("src"));
  420. }
  421. if (this.options.removeVideoSrc) {
  422. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  423. if (this.options.displayStats) {
  424. this.stats.discarded.videoSource = objectElements.length;
  425. }
  426. videoSourceElements.forEach(element => element.removeAttribute("src"));
  427. }
  428. }
  429. removeBase() {
  430. this.doc.querySelectorAll("base").forEach(element => element.remove());
  431. }
  432. removeInfoToolbar() {
  433. this.doc.querySelectorAll("singlefile-infobar").forEach(element => element.remove());
  434. }
  435. removeScripts() {
  436. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  437. if (this.options.displayStats) {
  438. this.stats.discarded.scripts = scriptElements.length;
  439. }
  440. scriptElements.forEach(element => element.remove());
  441. }
  442. removeFrames() {
  443. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  444. if (this.options.displayStats) {
  445. this.stats.discarded.frames = frameElements.length;
  446. }
  447. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  448. }
  449. removeImports() {
  450. const importElements = this.doc.querySelectorAll("link[rel=import]");
  451. if (this.options.displayStats) {
  452. this.stats.discarded.imports = importElements.length;
  453. }
  454. importElements.forEach(element => element.remove());
  455. }
  456. resetCharsetMeta() {
  457. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  458. const metaElement = this.doc.createElement("meta");
  459. metaElement.setAttribute("charset", "utf-8");
  460. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  461. }
  462. insertFaviconLink() {
  463. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  464. if (!faviconElement) {
  465. faviconElement = this.doc.createElement("link");
  466. faviconElement.setAttribute("type", "image/x-icon");
  467. faviconElement.setAttribute("rel", "shortcut icon");
  468. faviconElement.setAttribute("href", "/favicon.ico");
  469. this.doc.head.appendChild(faviconElement);
  470. }
  471. }
  472. resolveHrefs() {
  473. this.doc.querySelectorAll("[href]").forEach(element => {
  474. const match = element.href && element.href.match(/(.*)#.*$/);
  475. if (!match || match[1] != this.baseURI) {
  476. element.setAttribute("href", element.href);
  477. }
  478. });
  479. }
  480. removeUnusedCSSRules() {
  481. const stats = this.dom.rulesMinifier(this.doc);
  482. if (this.options.displayStats) {
  483. this.stats.processed.cssRules = stats.processed;
  484. this.stats.discarded.cssRules = stats.discarded;
  485. }
  486. }
  487. removeHiddenElements() {
  488. const hiddenElements = this.doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]");
  489. if (this.options.displayStats) {
  490. this.stats.discarded.hiddenElements = hiddenElements.length;
  491. }
  492. hiddenElements.forEach(element => element.remove());
  493. }
  494. compressHTML(postProcess) {
  495. if (postProcess) {
  496. let size;
  497. if (this.options.displayStats) {
  498. size = new Blob([this.doc.documentElement.outerHTML]).size;
  499. }
  500. this.dom.htmlmini.postProcess(this.doc);
  501. if (this.options.displayStats) {
  502. this.stats.discarded.htmlBytes += size - (new Blob([this.doc.documentElement.outerHTML]).size);
  503. }
  504. } else {
  505. let size;
  506. if (this.options.displayStats) {
  507. size = new Blob([this.doc.documentElement.outerHTML]).size;
  508. }
  509. this.dom.htmlmini.process(this.doc, { preservedSpaceAttributeName: PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME });
  510. if (this.options.displayStats) {
  511. this.stats.discarded.htmlBytes += size - (new Blob([this.doc.documentElement.outerHTML]).size);
  512. }
  513. this.doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  514. }
  515. }
  516. insertSingleFileCommentNode() {
  517. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  518. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  519. }
  520. replaceCanvasElements() {
  521. if (this.options.canvasData) {
  522. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  523. const canvasData = this.options.canvasData[indexCanvasElement];
  524. if (canvasData) {
  525. const imgElement = this.doc.createElement("img");
  526. imgElement.setAttribute("src", canvasData.dataURI);
  527. Array.from(canvasElement.attributes).forEach(attribute => {
  528. if (attribute.value) {
  529. imgElement.setAttribute(attribute.name, attribute.value);
  530. }
  531. });
  532. if (!imgElement.width && canvasData.width) {
  533. imgElement.style.pixelWidth = canvasData.width;
  534. }
  535. if (!imgElement.height && canvasData.height) {
  536. imgElement.style.pixelHeight = canvasData.height;
  537. }
  538. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  539. if (this.options.displayStats) {
  540. this.stats.processed.canvas++;
  541. }
  542. }
  543. });
  544. }
  545. }
  546. replaceEmptyStyles() {
  547. if (this.options.emptyStyleRulesText) {
  548. let indexStyle = 0;
  549. this.doc.querySelectorAll("style").forEach(styleElement => {
  550. if (!styleElement.textContent) {
  551. styleElement.textContent = this.options.emptyStyleRulesText[indexStyle];
  552. indexStyle++;
  553. }
  554. });
  555. }
  556. }
  557. async pageResources() {
  558. const resourcePromises = [
  559. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  560. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"], embed[src*=\".svg\"]"), "src", this.baseURI),
  561. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  562. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  563. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  564. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI, this.dom.parseSrcset)
  565. ];
  566. if (!this.options.removeAudioSrc) {
  567. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  568. }
  569. if (!this.options.removeVideoSrc) {
  570. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  571. }
  572. if (this.options.lazyLoadImages) {
  573. const imageSelectors = this.dom.lazyLoader.imageSelectors;
  574. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  575. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI, this.dom.parseSrcset)));
  576. }
  577. await resourcePromises;
  578. }
  579. async inlineStylesheets(initialization) {
  580. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  581. if (!initialization && this.options.displayStats) {
  582. this.stats.processed.styleSheets++;
  583. }
  584. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled }) : await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  585. styleElement.textContent = !initialization && this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  586. }));
  587. }
  588. async scripts() {
  589. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  590. if (scriptElement.src) {
  591. if (this.options.displayStats) {
  592. this.stats.processed.scripts++;
  593. }
  594. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  595. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  596. }
  597. scriptElement.removeAttribute("src");
  598. }));
  599. }
  600. async frames(initialization) {
  601. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  602. await Promise.all(frameElements.map(async frameElement => {
  603. DomProcessorHelper.setFrameEmptySrc(frameElement);
  604. frameElement.setAttribute("sandbox", "");
  605. const frameWindowId = frameElement.getAttribute(WIN_ID_ATTRIBUTE_NAME);
  606. if (frameWindowId) {
  607. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  608. if (frameData) {
  609. if (initialization) {
  610. const options = Object.create(this.options);
  611. options.insertSingleFileComment = false;
  612. options.insertFaviconLink = false;
  613. options.url = frameData.baseURI;
  614. options.windowId = frameWindowId;
  615. if (frameData.content) {
  616. options.content = frameData.content;
  617. options.canvasData = frameData.canvasData;
  618. options.emptyStyleRulesText = frameData.emptyStyleRulesText;
  619. frameData.processor = new PageProcessor(options);
  620. frameData.frameElement = frameElement;
  621. await frameData.processor.loadPage();
  622. return frameData.processor.initialize();
  623. }
  624. } else {
  625. if (frameData.processor) {
  626. if (this.options.displayStats) {
  627. this.stats.processed.frames++;
  628. }
  629. await frameData.processor.preparePageData();
  630. const pageData = await frameData.processor.getPageData();
  631. frameElement.removeAttribute(WIN_ID_ATTRIBUTE_NAME);
  632. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  633. if (this.options.displayStats) {
  634. Object.keys(this.stats.discarded).forEach(key => this.stats.discarded[key] += (pageData.stats.discarded[key] || 0));
  635. Object.keys(this.stats.processed).forEach(key => this.stats.processed[key] += (pageData.stats.processed[key] || 0));
  636. }
  637. } else if (this.options.displayStats) {
  638. this.stats.discarded.frames++;
  639. }
  640. }
  641. }
  642. }
  643. }));
  644. }
  645. async htmlImports(initialization) {
  646. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  647. if (!this.relImportProcessors) {
  648. this.relImportProcessors = new Map();
  649. }
  650. await Promise.all(linkElements.map(async linkElement => {
  651. if (initialization) {
  652. const resourceURL = linkElement.href;
  653. const options = Object.create(this.options);
  654. options.insertSingleFileComment = false;
  655. options.insertFaviconLink = false;
  656. options.url = resourceURL;
  657. if (resourceURL) {
  658. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  659. const processor = new PageProcessor(options);
  660. this.relImportProcessors.set(linkElement, processor);
  661. await processor.loadPage();
  662. return processor.initialize();
  663. }
  664. }
  665. } else {
  666. linkElement.setAttribute("href", EMPTY_DATA_URI);
  667. const processor = this.relImportProcessors.get(linkElement);
  668. if (processor) {
  669. if (this.options.displayStats) {
  670. this.stats.processed.imports++;
  671. }
  672. this.relImportProcessors.delete(linkElement);
  673. const pageData = await processor.getPageData();
  674. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  675. if (this.options.displayStats) {
  676. Object.keys(this.stats.discarded).forEach(key => this.stats.discarded[key] += (pageData.stats.discarded[key] || 0));
  677. Object.keys(this.stats.processed).forEach(key => this.stats.processed[key] += (pageData.stats.processed[key] || 0));
  678. }
  679. } else if (this.options.displayStats) {
  680. this.stats.discarded.imports++;
  681. }
  682. }
  683. }));
  684. }
  685. async attributeStyles(initialization) {
  686. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  687. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(element.getAttribute("style"), this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled }) : await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  688. element.setAttribute("style", this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent);
  689. }));
  690. }
  691. async linkStylesheets() {
  692. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  693. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  694. const styleElement = this.doc.createElement("style");
  695. styleElement.textContent = stylesheetContent;
  696. linkElement.parentElement.replaceChild(styleElement, linkElement);
  697. }));
  698. }
  699. }
  700. // ---------
  701. // DomHelper
  702. // ---------
  703. class DomProcessorHelper {
  704. static setFrameEmptySrc(frameElement) {
  705. if (frameElement.tagName == "OBJECT") {
  706. frameElement.setAttribute("data", "data:text/html,");
  707. } else {
  708. frameElement.setAttribute("srcdoc", "");
  709. frameElement.removeAttribute("src");
  710. }
  711. }
  712. static setFrameContent(frameElement, content) {
  713. if (frameElement.tagName == "OBJECT") {
  714. frameElement.setAttribute("data", "data:text/html," + content);
  715. } else {
  716. frameElement.setAttribute("srcdoc", content);
  717. frameElement.removeAttribute("src");
  718. }
  719. }
  720. static isolateElements(rootElement) {
  721. rootElement.querySelectorAll("*").forEach(element => {
  722. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  723. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  724. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  725. element.remove();
  726. }
  727. });
  728. isolateParentElements(rootElement.parentElement, rootElement);
  729. function isolateParentElements(parentElement, element) {
  730. if (parentElement) {
  731. Array.from(parentElement.childNodes).forEach(node => {
  732. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  733. node.remove();
  734. }
  735. });
  736. }
  737. element = element.parentElement;
  738. if (element && element.parentElement) {
  739. isolateParentElements(element.parentElement, element);
  740. }
  741. }
  742. }
  743. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  744. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  745. const imports = DomUtil.getImportFunctions(stylesheetContent);
  746. await Promise.all(imports.map(async cssImport => {
  747. const match = DomUtil.matchImport(cssImport);
  748. if (match) {
  749. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  750. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  751. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  752. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  753. if (stylesheetContent.indexOf(cssImport) != -1) {
  754. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  755. }
  756. }
  757. }
  758. }));
  759. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  760. if (imports.length) {
  761. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI, options);
  762. } else {
  763. return stylesheetContent;
  764. }
  765. }
  766. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  767. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  768. urlFunctions.map(urlFunction => {
  769. let resourceURL = DomUtil.matchURL(urlFunction);
  770. resourceURL = DomUtil.normalizeURL(resourceURL);
  771. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  772. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  773. }
  774. });
  775. return stylesheetContent;
  776. }
  777. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  778. resourceURL = DomUtil.normalizeURL(resourceURL);
  779. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  780. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  781. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  782. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  783. return stylesheetContent;
  784. }
  785. }
  786. static async processStylesheet(stylesheetContent, baseURI) {
  787. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  788. await Promise.all(urlFunctions.map(async urlFunction => {
  789. let resourceURL = DomUtil.matchURL(urlFunction);
  790. resourceURL = DomUtil.normalizeURL(resourceURL);
  791. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  792. const dataURI = await batchRequest.addURL(resourceURL);
  793. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  794. }
  795. }));
  796. return stylesheetContent;
  797. }
  798. static async processAttribute(resourceElements, attributeName, baseURI) {
  799. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  800. let resourceURL = resourceElement.getAttribute(attributeName);
  801. if (resourceURL) {
  802. resourceURL = DomUtil.normalizeURL(resourceURL);
  803. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  804. try {
  805. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  806. resourceElement.setAttribute(attributeName, dataURI);
  807. } catch (error) {
  808. /* ignored */
  809. }
  810. }
  811. }
  812. }));
  813. }
  814. static async processSrcset(resourceElements, attributeName, baseURI, parseSrcset) {
  815. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  816. const srcset = parseSrcset(resourceElement.getAttribute(attributeName));
  817. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  818. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  819. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  820. try {
  821. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  822. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  823. } catch (error) {
  824. /* ignored */
  825. }
  826. }
  827. }));
  828. resourceElement.setAttribute(attributeName, srcsetValues.join(","));
  829. }));
  830. }
  831. }
  832. // -------
  833. // DomUtil
  834. // -------
  835. const DATA_URI_PREFIX = "data:";
  836. const BLOB_URI_PREFIX = "blob:";
  837. const ABOUT_BLANK_URI = "about:blank";
  838. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  839. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  840. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  841. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  842. const REGEXP_IMPORT_FN = /(@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?);?)|(@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?);?)|(@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?);?)|(@import\s*'(.*?)'\s*(.*?);?)|(@import\s*"(.*?)"\s*(.*?);?)|(@import\s*(.*?)\s*(.*?);?)/gi;
  843. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  844. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  845. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  846. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  847. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  848. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  849. class DomUtil {
  850. static normalizeURL(url) {
  851. return url.split("#")[0];
  852. }
  853. static getUrlFunctions(stylesheetContent) {
  854. return stylesheetContent.match(REGEXP_URL_FN) || [];
  855. }
  856. static getImportFunctions(stylesheetContent) {
  857. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  858. }
  859. static matchURL(stylesheetContent) {
  860. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  861. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  862. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  863. return match && match[1];
  864. }
  865. static testValidPath(resourceURL) {
  866. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  867. }
  868. static matchImport(stylesheetContent) {
  869. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  870. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  871. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  872. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  873. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  874. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  875. if (match) {
  876. const [, resourceURL, media] = match;
  877. return { resourceURL, media };
  878. }
  879. }
  880. static removeCssComments(stylesheetContent) {
  881. let start, end;
  882. do {
  883. start = stylesheetContent.indexOf("/*");
  884. end = stylesheetContent.indexOf("*/", start);
  885. if (start != -1 && end != -1) {
  886. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  887. }
  888. } while (start != -1 && end != -1);
  889. return stylesheetContent;
  890. }
  891. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  892. if (mediaQuery) {
  893. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  894. } else {
  895. return stylesheetContent;
  896. }
  897. }
  898. }
  899. return { getClass };
  900. })();