single-file-core.js 37 KB

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