single-file-core.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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.content = this.options.content || (this.options.doc ? DOMProcessor.serialize(this.options.doc, false) : null);
  70. this.options.url = this.options.url || this.options.doc.location.href;
  71. this.processor = new DOMProcessor(options);
  72. if (this.options.doc) {
  73. this.options.canvasData = this.processor.getCanvasData();
  74. this.options.emptyStyleRulesText = this.processor.getEmptyStyleRulesText();
  75. this.processor.fixInlineScripts();
  76. this.processor.disableNoscriptElements();
  77. this.processor.hideNonMetadataContents();
  78. if (this.options.removeHiddenElements) {
  79. this.processor.markRemovedElements();
  80. }
  81. if (this.options.compressHTML) {
  82. this.processor.markPreservedElements();
  83. }
  84. }
  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 batchRequest = new BatchRequest();
  229. class DOMProcessor {
  230. constructor(options) {
  231. this.options = options;
  232. if (this.options.displayStats) {
  233. this.stats = {
  234. discarded: {
  235. htmlBytes: 0,
  236. hiddenElements: 0,
  237. imports: 0,
  238. scripts: 0,
  239. objects: 0,
  240. audioSource: 0,
  241. videoSource: 0,
  242. frames: 0,
  243. cssRules: 0,
  244. canvas: 0,
  245. styleSheets: 0,
  246. resources: 0
  247. },
  248. processed: {
  249. htmlBytes: 0,
  250. hiddenElements: 0,
  251. imports: 0,
  252. scripts: 0,
  253. objects: 0,
  254. audioSource: 0,
  255. videoSource: 0,
  256. frames: 0,
  257. cssRules: 0,
  258. canvas: 0,
  259. styleSheets: 0,
  260. resources: 0
  261. }
  262. };
  263. }
  264. this.baseURI = options.url;
  265. }
  266. static serialize(doc, compressHTML) {
  267. return DOM.serialize(doc, compressHTML);
  268. }
  269. async loadPage(pageContent) {
  270. if (!pageContent || this.options.saveRawPage) {
  271. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  272. }
  273. this.dom = DOM.create(pageContent, this.baseURI);
  274. this.DOMParser = this.dom.DOMParser;
  275. this.doc = this.dom.document;
  276. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  277. await DOMProcessor.loadEscapedFragmentPage();
  278. }
  279. }
  280. async loadEscapedFragmentPage() {
  281. if (this.baseURI.includes("?")) {
  282. this.baseURI += "&";
  283. } else {
  284. this.baseURI += "?";
  285. }
  286. this.baseURI += ESCAPED_FRAGMENT;
  287. await this.loadPage();
  288. }
  289. async retrieveResources(onloadListener) {
  290. if (this.options.displayStats) {
  291. this.stats.processed.resources = batchRequest.getMaxResources();
  292. }
  293. await batchRequest.run(onloadListener, this.options);
  294. }
  295. getPageData() {
  296. if (this.options.selected) {
  297. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  298. if (rootElement) {
  299. DomProcessorHelper.isolateElements(rootElement);
  300. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  301. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  302. }
  303. }
  304. const titleElement = this.doc.querySelector("title");
  305. let title;
  306. if (titleElement) {
  307. title = titleElement.textContent.trim();
  308. }
  309. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  310. let size;
  311. if (this.options.displayStats) {
  312. size = new Blob([this.doc.documentElement.outerHTML]).size;
  313. }
  314. const content = DOMProcessor.serialize(this.doc, this.options.compressHTML);
  315. if (this.options.displayStats) {
  316. this.stats.processed.htmlBytes = new Blob([content]).size;
  317. this.stats.discarded.htmlBytes += size - this.stats.processed.htmlBytes;
  318. }
  319. return {
  320. stats: this.stats,
  321. title: title || (this.baseURI && matchTitle ? matchTitle[1] : ""),
  322. content
  323. };
  324. }
  325. fixInlineScripts() {
  326. this.options.doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  327. }
  328. disableNoscriptElements() {
  329. this.options.doc.head.querySelectorAll("noscript").forEach(element => {
  330. const disabledNoscriptElement = this.options.doc.createElement("disabled-noscript");
  331. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  332. disabledNoscriptElement.hidden = true;
  333. element.parentElement.replaceChild(disabledNoscriptElement, element);
  334. });
  335. }
  336. hideNonMetadataContents() {
  337. 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);
  338. }
  339. markRemovedElements() {
  340. this.options.doc.querySelectorAll("html > body *:not(style):not(script):not(link):not(frame):not(iframe):not(object)").forEach(element => {
  341. const style = this.options.win.getComputedStyle(element);
  342. 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]")) {
  343. element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
  344. }
  345. });
  346. }
  347. markPreservedElements() {
  348. this.options.doc.querySelectorAll("*").forEach(element => {
  349. const style = this.options.win.getComputedStyle(element);
  350. if (style.whiteSpace.startsWith("pre")) {
  351. element.setAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, "");
  352. }
  353. });
  354. }
  355. displayHiddenNonMetadataContents() {
  356. 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"));
  357. }
  358. unmarkPreservedElements() {
  359. this.options.doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  360. }
  361. unmarkRemovedElements() {
  362. this.options.doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  363. }
  364. removeWindowIdFrames() {
  365. this.options.doc.querySelectorAll("[" + WIN_ID_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(WIN_ID_ATTRIBUTE_NAME));
  366. }
  367. getEmptyStyleRulesText() {
  368. const textData = [];
  369. this.options.doc.querySelectorAll("style").forEach(styleElement => {
  370. if (!styleElement.textContent) {
  371. textData.push(Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n"));
  372. }
  373. });
  374. return textData;
  375. }
  376. getCanvasData() {
  377. const canvasData = [];
  378. this.options.doc.querySelectorAll("canvas").forEach(canvasElement => {
  379. try {
  380. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: canvasElement.clientWidth, height: canvasElement.clientHeight });
  381. } catch (error) {
  382. canvasData.push(null);
  383. }
  384. });
  385. return canvasData;
  386. }
  387. enableDisabledNoscriptTags(noscriptTags) {
  388. noscriptTags.forEach(element => {
  389. const noscriptElement = this.options.doc.createElement("noscript");
  390. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  391. element.parentElement.replaceChild(noscriptElement, element);
  392. });
  393. }
  394. insertNoscriptContents() {
  395. if (this.DOMParser) {
  396. this.doc.querySelectorAll("noscript").forEach(element => {
  397. const fragment = this.doc.createDocumentFragment();
  398. Array.from(element.childNodes).forEach(node => {
  399. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  400. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  401. this.doc.importNode(node);
  402. fragment.appendChild(node);
  403. });
  404. });
  405. element.parentElement.replaceChild(fragment, element);
  406. });
  407. }
  408. }
  409. lazyLoadImages() {
  410. this.dom.lazyLoader.process(this.doc);
  411. }
  412. removeDiscardedResources() {
  413. 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]");
  414. if (this.options.displayStats) {
  415. this.stats.discarded.objects = objectElements.length;
  416. }
  417. objectElements.forEach(element => element.remove());
  418. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  419. this.doc.querySelectorAll("[onerror]").forEach(element => element.removeAttribute("onerror"));
  420. if (this.options.removeAudioSrc) {
  421. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  422. if (this.options.displayStats) {
  423. this.stats.discarded.audioSource = objectElements.length;
  424. }
  425. audioSourceElements.forEach(element => element.removeAttribute("src"));
  426. }
  427. if (this.options.removeVideoSrc) {
  428. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  429. if (this.options.displayStats) {
  430. this.stats.discarded.videoSource = objectElements.length;
  431. }
  432. videoSourceElements.forEach(element => element.removeAttribute("src"));
  433. }
  434. }
  435. removeBase() {
  436. this.doc.querySelectorAll("base").forEach(element => element.remove());
  437. }
  438. removeInfoToolbar() {
  439. this.doc.querySelectorAll("singlefile-infobar").forEach(element => element.remove());
  440. }
  441. removeScripts() {
  442. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  443. if (this.options.displayStats) {
  444. this.stats.discarded.scripts = scriptElements.length;
  445. }
  446. scriptElements.forEach(element => element.remove());
  447. }
  448. removeFrames() {
  449. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  450. if (this.options.displayStats) {
  451. this.stats.discarded.frames = frameElements.length;
  452. }
  453. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  454. }
  455. removeImports() {
  456. const importElements = this.doc.querySelectorAll("link[rel=import]");
  457. if (this.options.displayStats) {
  458. this.stats.discarded.imports = importElements.length;
  459. }
  460. importElements.forEach(element => element.remove());
  461. }
  462. resetCharsetMeta() {
  463. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  464. const metaElement = this.doc.createElement("meta");
  465. metaElement.setAttribute("charset", "utf-8");
  466. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  467. }
  468. insertFaviconLink() {
  469. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  470. if (!faviconElement) {
  471. faviconElement = this.doc.createElement("link");
  472. faviconElement.setAttribute("type", "image/x-icon");
  473. faviconElement.setAttribute("rel", "shortcut icon");
  474. faviconElement.setAttribute("href", "/favicon.ico");
  475. this.doc.head.appendChild(faviconElement);
  476. }
  477. }
  478. resolveHrefs() {
  479. this.doc.querySelectorAll("[href]").forEach(element => {
  480. const match = element.href && element.href.match(/(.*)#.*$/);
  481. if (!match || match[1] != this.baseURI) {
  482. element.setAttribute("href", element.href);
  483. }
  484. });
  485. }
  486. removeUnusedCSSRules() {
  487. const stats = this.dom.rulesMinifier(this.doc);
  488. if (this.options.displayStats) {
  489. this.stats.processed.cssRules = stats.processed;
  490. this.stats.discarded.cssRules = stats.discarded;
  491. }
  492. }
  493. removeHiddenElements() {
  494. const hiddenElements = this.doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]");
  495. if (this.options.displayStats) {
  496. this.stats.discarded.hiddenElements = hiddenElements.length;
  497. }
  498. hiddenElements.forEach(element => element.remove());
  499. }
  500. compressHTML(postProcess) {
  501. if (postProcess) {
  502. let size;
  503. if (this.options.displayStats) {
  504. size = new Blob([this.doc.documentElement.outerHTML]).size;
  505. }
  506. this.dom.htmlmini.postProcess(this.doc);
  507. if (this.options.displayStats) {
  508. this.stats.discarded.htmlBytes += size - (new Blob([this.doc.documentElement.outerHTML]).size);
  509. }
  510. } else {
  511. let size;
  512. if (this.options.displayStats) {
  513. size = new Blob([this.doc.documentElement.outerHTML]).size;
  514. }
  515. this.dom.htmlmini.process(this.doc, { preservedSpaceAttributeName: PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME });
  516. if (this.options.displayStats) {
  517. this.stats.discarded.htmlBytes += size - (new Blob([this.doc.documentElement.outerHTML]).size);
  518. }
  519. this.doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  520. }
  521. }
  522. insertSingleFileCommentNode() {
  523. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  524. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  525. }
  526. replaceCanvasElements() {
  527. if (this.options.canvasData) {
  528. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  529. const canvasData = this.options.canvasData[indexCanvasElement];
  530. if (canvasData) {
  531. const imgElement = this.doc.createElement("img");
  532. imgElement.setAttribute("src", canvasData.dataURI);
  533. Array.from(canvasElement.attributes).forEach(attribute => {
  534. if (attribute.value) {
  535. imgElement.setAttribute(attribute.name, attribute.value);
  536. }
  537. });
  538. if (!imgElement.width && canvasData.width) {
  539. imgElement.style.pixelWidth = canvasData.width;
  540. }
  541. if (!imgElement.height && canvasData.height) {
  542. imgElement.style.pixelHeight = canvasData.height;
  543. }
  544. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  545. if (this.options.displayStats) {
  546. this.stats.processed.canvas++;
  547. }
  548. }
  549. });
  550. }
  551. }
  552. replaceEmptyStyles() {
  553. if (this.options.emptyStyleRulesText) {
  554. let indexStyle = 0;
  555. this.doc.querySelectorAll("style").forEach(styleElement => {
  556. if (!styleElement.textContent) {
  557. styleElement.textContent = this.options.emptyStyleRulesText[indexStyle];
  558. indexStyle++;
  559. }
  560. });
  561. }
  562. }
  563. async pageResources() {
  564. const resourcePromises = [
  565. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  566. 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),
  567. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  568. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  569. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  570. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI, this.dom.parseSrcset)
  571. ];
  572. if (!this.options.removeAudioSrc) {
  573. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  574. }
  575. if (!this.options.removeVideoSrc) {
  576. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  577. }
  578. if (this.options.lazyLoadImages) {
  579. const imageSelectors = this.dom.lazyLoader.imageSelectors;
  580. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  581. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI, this.dom.parseSrcset)));
  582. }
  583. await resourcePromises;
  584. }
  585. async inlineStylesheets(initialization) {
  586. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  587. if (!initialization && this.options.displayStats) {
  588. this.stats.processed.styleSheets++;
  589. }
  590. 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);
  591. styleElement.textContent = !initialization && this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  592. }));
  593. }
  594. async scripts() {
  595. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  596. if (scriptElement.src) {
  597. if (this.options.displayStats) {
  598. this.stats.processed.scripts++;
  599. }
  600. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  601. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  602. }
  603. scriptElement.removeAttribute("src");
  604. }));
  605. }
  606. async frames(initialization) {
  607. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  608. await Promise.all(frameElements.map(async frameElement => {
  609. DomProcessorHelper.setFrameEmptySrc(frameElement);
  610. frameElement.setAttribute("sandbox", "");
  611. const frameWindowId = frameElement.getAttribute(WIN_ID_ATTRIBUTE_NAME);
  612. if (frameWindowId) {
  613. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  614. if (frameData) {
  615. if (initialization) {
  616. const options = Object.create(this.options);
  617. options.insertSingleFileComment = false;
  618. options.insertFaviconLink = false;
  619. options.url = frameData.baseURI;
  620. options.windowId = frameWindowId;
  621. if (frameData.content) {
  622. options.content = frameData.content;
  623. options.canvasData = frameData.canvasData;
  624. options.emptyStyleRulesText = frameData.emptyStyleRulesText;
  625. frameData.processor = new PageProcessor(options);
  626. frameData.frameElement = frameElement;
  627. await frameData.processor.loadPage();
  628. return frameData.processor.initialize();
  629. }
  630. } else {
  631. if (frameData.processor) {
  632. if (this.options.displayStats) {
  633. this.stats.processed.frames++;
  634. }
  635. await frameData.processor.preparePageData();
  636. const pageData = await frameData.processor.getPageData();
  637. frameElement.removeAttribute(WIN_ID_ATTRIBUTE_NAME);
  638. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  639. if (this.options.displayStats) {
  640. Object.keys(this.stats.discarded).forEach(key => this.stats.discarded[key] += (pageData.stats.discarded[key] || 0));
  641. Object.keys(this.stats.processed).forEach(key => this.stats.processed[key] += (pageData.stats.processed[key] || 0));
  642. }
  643. } else if (this.options.displayStats) {
  644. this.stats.discarded.frames++;
  645. }
  646. }
  647. }
  648. }
  649. }));
  650. }
  651. async htmlImports(initialization) {
  652. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  653. if (!this.relImportProcessors) {
  654. this.relImportProcessors = new Map();
  655. }
  656. await Promise.all(linkElements.map(async linkElement => {
  657. if (initialization) {
  658. const resourceURL = linkElement.href;
  659. const options = Object.create(this.options);
  660. options.insertSingleFileComment = false;
  661. options.insertFaviconLink = false;
  662. options.url = resourceURL;
  663. if (resourceURL) {
  664. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  665. const processor = new PageProcessor(options);
  666. this.relImportProcessors.set(linkElement, processor);
  667. await processor.loadPage();
  668. return processor.initialize();
  669. }
  670. }
  671. } else {
  672. linkElement.setAttribute("href", EMPTY_DATA_URI);
  673. const processor = this.relImportProcessors.get(linkElement);
  674. if (processor) {
  675. if (this.options.displayStats) {
  676. this.stats.processed.imports++;
  677. }
  678. this.relImportProcessors.delete(linkElement);
  679. const pageData = await processor.getPageData();
  680. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  681. if (this.options.displayStats) {
  682. Object.keys(this.stats.discarded).forEach(key => this.stats.discarded[key] += (pageData.stats.discarded[key] || 0));
  683. Object.keys(this.stats.processed).forEach(key => this.stats.processed[key] += (pageData.stats.processed[key] || 0));
  684. }
  685. } else if (this.options.displayStats) {
  686. this.stats.discarded.imports++;
  687. }
  688. }
  689. }));
  690. }
  691. async attributeStyles(initialization) {
  692. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  693. 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);
  694. element.setAttribute("style", this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent);
  695. }));
  696. }
  697. async linkStylesheets() {
  698. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  699. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  700. const styleElement = this.doc.createElement("style");
  701. styleElement.textContent = stylesheetContent;
  702. linkElement.parentElement.replaceChild(styleElement, linkElement);
  703. }));
  704. }
  705. }
  706. // ---------
  707. // DomHelper
  708. // ---------
  709. class DomProcessorHelper {
  710. static setFrameEmptySrc(frameElement) {
  711. if (frameElement.tagName == "OBJECT") {
  712. frameElement.setAttribute("data", "data:text/html,");
  713. } else {
  714. frameElement.setAttribute("srcdoc", "");
  715. frameElement.removeAttribute("src");
  716. }
  717. }
  718. static setFrameContent(frameElement, content) {
  719. if (frameElement.tagName == "OBJECT") {
  720. frameElement.setAttribute("data", "data:text/html," + content);
  721. } else {
  722. frameElement.setAttribute("srcdoc", content);
  723. frameElement.removeAttribute("src");
  724. }
  725. }
  726. static isolateElements(rootElement) {
  727. rootElement.querySelectorAll("*").forEach(element => {
  728. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  729. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  730. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  731. element.remove();
  732. }
  733. });
  734. isolateParentElements(rootElement.parentElement, rootElement);
  735. function isolateParentElements(parentElement, element) {
  736. if (parentElement) {
  737. Array.from(parentElement.childNodes).forEach(node => {
  738. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  739. node.remove();
  740. }
  741. });
  742. }
  743. element = element.parentElement;
  744. if (element && element.parentElement) {
  745. isolateParentElements(element.parentElement, element);
  746. }
  747. }
  748. }
  749. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  750. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  751. const imports = DomUtil.getImportFunctions(stylesheetContent);
  752. await Promise.all(imports.map(async cssImport => {
  753. const match = DomUtil.matchImport(cssImport);
  754. if (match) {
  755. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  756. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  757. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  758. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  759. if (stylesheetContent.indexOf(cssImport) != -1) {
  760. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  761. }
  762. }
  763. }
  764. }));
  765. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  766. if (imports.length) {
  767. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI, options);
  768. } else {
  769. return stylesheetContent;
  770. }
  771. }
  772. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  773. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  774. urlFunctions.map(urlFunction => {
  775. let resourceURL = DomUtil.matchURL(urlFunction);
  776. resourceURL = DomUtil.normalizeURL(resourceURL);
  777. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  778. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  779. }
  780. });
  781. return stylesheetContent;
  782. }
  783. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  784. resourceURL = DomUtil.normalizeURL(resourceURL);
  785. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  786. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  787. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  788. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  789. return stylesheetContent;
  790. }
  791. }
  792. static async processStylesheet(stylesheetContent, baseURI) {
  793. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  794. await Promise.all(urlFunctions.map(async urlFunction => {
  795. let resourceURL = DomUtil.matchURL(urlFunction);
  796. resourceURL = DomUtil.normalizeURL(resourceURL);
  797. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  798. const dataURI = await batchRequest.addURL(resourceURL);
  799. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  800. }
  801. }));
  802. return stylesheetContent;
  803. }
  804. static async processAttribute(resourceElements, attributeName, baseURI) {
  805. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  806. let resourceURL = resourceElement.getAttribute(attributeName);
  807. if (resourceURL) {
  808. resourceURL = DomUtil.normalizeURL(resourceURL);
  809. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  810. try {
  811. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  812. resourceElement.setAttribute(attributeName, dataURI);
  813. } catch (error) {
  814. /* ignored */
  815. }
  816. }
  817. }
  818. }));
  819. }
  820. static async processSrcset(resourceElements, attributeName, baseURI, parseSrcset) {
  821. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  822. const srcset = parseSrcset(resourceElement.getAttribute(attributeName));
  823. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  824. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  825. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  826. try {
  827. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  828. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  829. } catch (error) {
  830. /* ignored */
  831. }
  832. }
  833. }));
  834. resourceElement.setAttribute(attributeName, srcsetValues.join(","));
  835. }));
  836. }
  837. }
  838. // -------
  839. // DomUtil
  840. // -------
  841. const DATA_URI_PREFIX = "data:";
  842. const BLOB_URI_PREFIX = "blob:";
  843. const ABOUT_BLANK_URI = "about:blank";
  844. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  845. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  846. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  847. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  848. 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;
  849. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  850. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  851. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  852. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  853. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  854. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  855. class DomUtil {
  856. static normalizeURL(url) {
  857. return url.split("#")[0];
  858. }
  859. static getUrlFunctions(stylesheetContent) {
  860. return stylesheetContent.match(REGEXP_URL_FN) || [];
  861. }
  862. static getImportFunctions(stylesheetContent) {
  863. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  864. }
  865. static matchURL(stylesheetContent) {
  866. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  867. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  868. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  869. return match && match[1];
  870. }
  871. static testValidPath(resourceURL) {
  872. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  873. }
  874. static matchImport(stylesheetContent) {
  875. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  876. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  877. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  878. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  879. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  880. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  881. if (match) {
  882. const [, resourceURL, media] = match;
  883. return { resourceURL, media };
  884. }
  885. }
  886. static removeCssComments(stylesheetContent) {
  887. let start, end;
  888. do {
  889. start = stylesheetContent.indexOf("/*");
  890. end = stylesheetContent.indexOf("*/", start);
  891. if (start != -1 && end != -1) {
  892. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  893. }
  894. } while (start != -1 && end != -1);
  895. return stylesheetContent;
  896. }
  897. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  898. if (mediaQuery) {
  899. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  900. } else {
  901. return stylesheetContent;
  902. }
  903. }
  904. }
  905. return { getClass };
  906. })();