single-file-core.js 34 KB

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