single-file-core.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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 = DomUtil.normalizeURL(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.querySelector("link[href][rel*=\"icon\"]");
  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. }
  357. this.doc.head.appendChild(faviconElement);
  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. let stylesheetContent = styleElement.textContent;
  478. if (initialization) {
  479. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  480. stylesheetContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  481. } else {
  482. stylesheetContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  483. }
  484. styleElement.textContent = stylesheetContent;
  485. }));
  486. }
  487. async scripts() {
  488. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  489. if (scriptElement.src) {
  490. this.stats.add("processed", "scripts", 1);
  491. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  492. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  493. }
  494. scriptElement.removeAttribute("src");
  495. }));
  496. }
  497. async frames(initialization) {
  498. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  499. await Promise.all(frameElements.map(async frameElement => {
  500. DomProcessorHelper.setFrameEmptySrc(frameElement);
  501. frameElement.setAttribute("sandbox", "");
  502. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  503. if (frameWindowId) {
  504. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  505. if (frameData) {
  506. if (initialization) {
  507. const options = Object.create(this.options);
  508. options.insertSingleFileComment = false;
  509. options.insertFaviconLink = false;
  510. options.doc = null;
  511. options.win = null;
  512. options.url = frameData.baseURI;
  513. options.windowId = frameWindowId;
  514. if (frameData.content) {
  515. options.content = frameData.content;
  516. options.canvasData = frameData.canvasData;
  517. options.emptyStyleRulesText = frameData.emptyStyleRulesText;
  518. frameData.processor = new PageProcessor(options);
  519. frameData.frameElement = frameElement;
  520. await frameData.processor.loadPage();
  521. return frameData.processor.initialize();
  522. }
  523. } else {
  524. if (frameData.processor) {
  525. this.stats.add("processed", "frames", 1);
  526. await frameData.processor.preparePageData();
  527. const pageData = await frameData.processor.getPageData();
  528. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  529. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  530. this.stats.addAll(pageData);
  531. } else {
  532. this.stats.add("discarded", "frames", 1);
  533. }
  534. }
  535. }
  536. }
  537. }));
  538. }
  539. async htmlImports(initialization) {
  540. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  541. if (!this.relImportProcessors) {
  542. this.relImportProcessors = new Map();
  543. }
  544. await Promise.all(linkElements.map(async linkElement => {
  545. if (initialization) {
  546. const resourceURL = linkElement.href;
  547. const options = Object.create(this.options);
  548. options.insertSingleFileComment = false;
  549. options.insertFaviconLink = false;
  550. options.doc = null;
  551. options.win = null;
  552. options.url = resourceURL;
  553. if (resourceURL) {
  554. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  555. const processor = new PageProcessor(options);
  556. this.relImportProcessors.set(linkElement, processor);
  557. await processor.loadPage();
  558. return processor.initialize();
  559. }
  560. }
  561. } else {
  562. linkElement.setAttribute("href", EMPTY_DATA_URI);
  563. const processor = this.relImportProcessors.get(linkElement);
  564. if (processor) {
  565. this.stats.add("processed", "imports", 1);
  566. this.relImportProcessors.delete(linkElement);
  567. const pageData = await processor.getPageData();
  568. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  569. this.stats.addAll(pageData);
  570. } else {
  571. this.stats.add("discarded", "imports", 1);
  572. }
  573. }
  574. }));
  575. }
  576. async attributeStyles(initialization) {
  577. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  578. let stylesheetContent = element.getAttribute("style");
  579. if (initialization) {
  580. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  581. } else {
  582. stylesheetContent = await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  583. }
  584. element.setAttribute("style", stylesheetContent);
  585. }));
  586. }
  587. async linkStylesheets() {
  588. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  589. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  590. const styleElement = this.doc.createElement("style");
  591. styleElement.textContent = stylesheetContent;
  592. linkElement.parentElement.replaceChild(styleElement, linkElement);
  593. }));
  594. }
  595. }
  596. // ---------
  597. // DomHelper
  598. // ---------
  599. class DomProcessorHelper {
  600. static setFrameEmptySrc(frameElement) {
  601. if (frameElement.tagName == "OBJECT") {
  602. frameElement.setAttribute("data", "data:text/html,");
  603. } else {
  604. frameElement.setAttribute("srcdoc", "");
  605. frameElement.removeAttribute("src");
  606. }
  607. }
  608. static setFrameContent(frameElement, content) {
  609. if (frameElement.tagName == "OBJECT") {
  610. frameElement.setAttribute("data", "data:text/html," + content);
  611. } else {
  612. frameElement.setAttribute("srcdoc", content);
  613. frameElement.removeAttribute("src");
  614. }
  615. }
  616. static isolateElements(rootElement) {
  617. rootElement.querySelectorAll("*").forEach(element => {
  618. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  619. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  620. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  621. element.remove();
  622. }
  623. });
  624. isolateParentElements(rootElement.parentElement, rootElement);
  625. function isolateParentElements(parentElement, element) {
  626. if (parentElement) {
  627. Array.from(parentElement.childNodes).forEach(node => {
  628. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  629. node.remove();
  630. }
  631. });
  632. }
  633. element = element.parentElement;
  634. if (element && element.parentElement) {
  635. isolateParentElements(element.parentElement, element);
  636. }
  637. }
  638. }
  639. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  640. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  641. const imports = DomUtil.getImportFunctions(stylesheetContent);
  642. await Promise.all(imports.map(async cssImport => {
  643. const match = DomUtil.matchImport(cssImport);
  644. if (match) {
  645. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  646. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  647. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  648. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  649. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  650. if (stylesheetContent.indexOf(cssImport) != -1) {
  651. importedStylesheetContent = DomProcessorHelper.resolveStylesheetURLs(importedStylesheetContent, styleSheetUrl);
  652. DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  653. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  654. }
  655. }
  656. }
  657. }));
  658. return stylesheetContent;
  659. }
  660. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  661. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  662. urlFunctions.map(urlFunction => {
  663. let resourceURL = DomUtil.matchURL(urlFunction);
  664. resourceURL = DomUtil.normalizeURL(resourceURL);
  665. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  666. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  667. }
  668. });
  669. return stylesheetContent;
  670. }
  671. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  672. resourceURL = DomUtil.normalizeURL(resourceURL);
  673. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  674. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  675. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, resourceURL);
  676. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  677. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  678. return stylesheetContent;
  679. }
  680. }
  681. static async processStylesheet(stylesheetContent, baseURI) {
  682. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  683. await Promise.all(urlFunctions.map(async urlFunction => {
  684. let resourceURL = DomUtil.matchURL(urlFunction);
  685. resourceURL = DomUtil.normalizeURL(resourceURL);
  686. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  687. const dataURI = await batchRequest.addURL(resourceURL);
  688. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  689. }
  690. }));
  691. return stylesheetContent;
  692. }
  693. static async processAttribute(resourceElements, attributeName, baseURI) {
  694. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  695. let resourceURL = resourceElement.getAttribute(attributeName);
  696. if (resourceURL) {
  697. resourceURL = DomUtil.normalizeURL(resourceURL);
  698. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  699. try {
  700. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  701. resourceElement.setAttribute(attributeName, dataURI);
  702. } catch (error) {
  703. /* ignored */
  704. }
  705. }
  706. }
  707. }));
  708. }
  709. static async processSrcset(resourceElements, attributeName, baseURI) {
  710. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  711. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  712. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  713. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  714. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  715. try {
  716. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  717. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  718. } catch (error) {
  719. /* ignored */
  720. }
  721. }
  722. }));
  723. resourceElement.setAttribute(attributeName, srcsetValues.join(","));
  724. }));
  725. }
  726. }
  727. // -------
  728. // DomUtil
  729. // -------
  730. const DATA_URI_PREFIX = "data:";
  731. const BLOB_URI_PREFIX = "blob:";
  732. const ABOUT_BLANK_URI = "about:blank";
  733. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  734. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  735. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  736. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  737. 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;
  738. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  739. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  740. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  741. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  742. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  743. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  744. class DomUtil {
  745. static normalizeURL(url) {
  746. return url.split("#")[0];
  747. }
  748. static getUrlFunctions(stylesheetContent) {
  749. return stylesheetContent.match(REGEXP_URL_FN) || [];
  750. }
  751. static getImportFunctions(stylesheetContent) {
  752. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  753. }
  754. static matchURL(stylesheetContent) {
  755. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  756. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  757. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  758. return match && match[1];
  759. }
  760. static testValidPath(resourceURL) {
  761. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  762. }
  763. static matchImport(stylesheetContent) {
  764. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  765. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  766. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  767. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  768. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  769. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  770. if (match) {
  771. const [, resourceURL, media] = match;
  772. return { resourceURL, media };
  773. }
  774. }
  775. static removeCssComments(stylesheetContent) {
  776. let start, end;
  777. do {
  778. start = stylesheetContent.indexOf("/*");
  779. end = stylesheetContent.indexOf("*/", start);
  780. if (start != -1 && end != -1) {
  781. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  782. }
  783. } while (start != -1 && end != -1);
  784. return stylesheetContent;
  785. }
  786. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  787. if (mediaQuery) {
  788. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  789. } else {
  790. return stylesheetContent;
  791. }
  792. }
  793. }
  794. // -----
  795. // Stats
  796. // -----
  797. const STATS_DEFAULT_VALUES = {
  798. discarded: {
  799. htmlBytes: 0,
  800. hiddenElements: 0,
  801. imports: 0,
  802. scripts: 0,
  803. objects: 0,
  804. audioSource: 0,
  805. videoSource: 0,
  806. frames: 0,
  807. cssRules: 0
  808. },
  809. processed: {
  810. htmlBytes: 0,
  811. imports: 0,
  812. scripts: 0,
  813. frames: 0,
  814. cssRules: 0,
  815. canvas: 0,
  816. styleSheets: 0,
  817. resources: 0
  818. }
  819. };
  820. class Stats {
  821. constructor(options) {
  822. this.options = options;
  823. if (options.displayStats) {
  824. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  825. }
  826. }
  827. set(type, subType, value) {
  828. if (this.options.displayStats) {
  829. this.data[type][subType] = value;
  830. }
  831. }
  832. add(type, subType, value) {
  833. if (this.options.displayStats) {
  834. this.data[type][subType] += value;
  835. }
  836. }
  837. addAll(pageData) {
  838. if (this.options.displayStats) {
  839. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  840. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  841. }
  842. }
  843. }
  844. return { getClass };
  845. })();