single-file-core.js 34 KB

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