single-file-core.js 33 KB

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