single-file-core.js 33 KB

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