single-file-core.js 33 KB

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