single-file-core.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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\"])");
  304. this.stats.set("discarded", "objects", objectElements.length);
  305. objectElements.forEach(element => element.remove());
  306. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  307. replacedAttributeValue.forEach(element => element.setAttribute("rel", element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "")));
  308. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  309. this.doc.querySelectorAll("[onerror]").forEach(element => element.removeAttribute("onerror"));
  310. if (this.options.removeAudioSrc) {
  311. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  312. this.stats.set("discarded", "audioSource", audioSourceElements.length);
  313. audioSourceElements.forEach(element => element.removeAttribute("src"));
  314. }
  315. if (this.options.removeVideoSrc) {
  316. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  317. this.stats.set("discarded", "videoSource", videoSourceElements.length);
  318. videoSourceElements.forEach(element => element.removeAttribute("src"));
  319. }
  320. }
  321. removeDefaultHeadTags() {
  322. this.doc.querySelectorAll("base").forEach(element => element.remove());
  323. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  324. this.doc.head.querySelector("meta[charset]").remove();
  325. }
  326. }
  327. removeUIElements() {
  328. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  329. }
  330. removeScripts() {
  331. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  332. this.stats.set("discarded", "scripts", scriptElements.length);
  333. scriptElements.forEach(element => element.remove());
  334. }
  335. removeFrames() {
  336. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  337. this.stats.set("discarded", "frames", frameElements.length);
  338. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  339. }
  340. removeImports() {
  341. const importElements = this.doc.querySelectorAll("link[rel=import]");
  342. this.stats.set("discarded", "imports", importElements.length);
  343. importElements.forEach(element => element.remove());
  344. }
  345. resetCharsetMeta() {
  346. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => element.remove());
  347. const metaElement = this.doc.createElement("meta");
  348. metaElement.setAttribute("charset", "utf-8");
  349. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  350. }
  351. insertFaviconLink() {
  352. let faviconElement = this.doc.querySelector("link[href][rel*=\"icon\"]");
  353. if (!faviconElement) {
  354. faviconElement = this.doc.createElement("link");
  355. faviconElement.setAttribute("type", "image/x-icon");
  356. faviconElement.setAttribute("rel", "shortcut icon");
  357. faviconElement.setAttribute("href", "/favicon.ico");
  358. }
  359. this.doc.head.appendChild(faviconElement);
  360. }
  361. resolveHrefs() {
  362. this.doc.querySelectorAll("[href]").forEach(element => {
  363. const match = element.href && element.href.match(/(.*)#.*$/);
  364. if (!match || match[1] != this.baseURI) {
  365. element.setAttribute("href", element.href);
  366. }
  367. });
  368. }
  369. removeUnusedStyles() {
  370. const stats = DOM.cssMinifier(this.doc);
  371. this.stats.set("processed", "cssRules", stats.processed);
  372. this.stats.set("discarded", "cssRules", stats.discarded);
  373. }
  374. removeAlternativeFonts(secondPass) {
  375. DOM.fontsMinifier(this.doc, secondPass);
  376. }
  377. removeHiddenElements(sessionId) {
  378. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(sessionId) + "]");
  379. this.stats.set("discarded", "hiddenElements", hiddenElements.length);
  380. hiddenElements.forEach(element => element.remove());
  381. }
  382. compressHTML(postProcess) {
  383. if (postProcess) {
  384. let size;
  385. if (this.options.displayStats) {
  386. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  387. }
  388. DOM.htmlminiPostProcess(this.doc);
  389. if (this.options.displayStats) {
  390. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  391. }
  392. } else {
  393. let size;
  394. if (this.options.displayStats) {
  395. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  396. }
  397. DOM.htmlminiProcess(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  398. if (this.options.displayStats) {
  399. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  400. }
  401. }
  402. }
  403. compressCSS() {
  404. this.doc.querySelectorAll("style").forEach(styleElement => {
  405. if (styleElement) {
  406. styleElement.textContent = DOM.uglifycss(styleElement.textContent);
  407. }
  408. });
  409. this.doc.querySelectorAll("[style]").forEach(element => {
  410. element.setAttribute("style", DOM.uglifycss(element.getAttribute("style")));
  411. });
  412. }
  413. insertSingleFileCommentNode() {
  414. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  415. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  416. }
  417. replaceCanvasElements() {
  418. if (this.options.canvasData) {
  419. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  420. const canvasData = this.options.canvasData[indexCanvasElement];
  421. if (canvasData) {
  422. const imgElement = this.doc.createElement("img");
  423. imgElement.setAttribute("src", canvasData.dataURI);
  424. Array.from(canvasElement.attributes).forEach(attribute => {
  425. if (attribute.value) {
  426. imgElement.setAttribute(attribute.name, attribute.value);
  427. }
  428. });
  429. if (!imgElement.width && canvasData.width) {
  430. imgElement.style.pixelWidth = canvasData.width;
  431. }
  432. if (!imgElement.height && canvasData.height) {
  433. imgElement.style.pixelHeight = canvasData.height;
  434. }
  435. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  436. this.stats.add("processed", "canvas", 1);
  437. }
  438. });
  439. }
  440. }
  441. replaceEmptyStyles() {
  442. if (this.options.emptyStyleRulesText) {
  443. let indexStyle = 0;
  444. this.doc.querySelectorAll("style").forEach(styleElement => {
  445. if (!styleElement.textContent) {
  446. styleElement.textContent = this.options.emptyStyleRulesText[indexStyle];
  447. indexStyle++;
  448. }
  449. });
  450. }
  451. }
  452. async pageResources() {
  453. const resourcePromises = [
  454. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  455. 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),
  456. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  457. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  458. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  459. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI)
  460. ];
  461. if (!this.options.removeAudioSrc) {
  462. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  463. }
  464. if (!this.options.removeVideoSrc) {
  465. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  466. }
  467. if (this.options.lazyLoadImages) {
  468. const imageSelectors = DOM.lazyLoaderImageSelectors();
  469. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  470. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI)));
  471. }
  472. await resourcePromises;
  473. }
  474. async inlineStylesheets(initialization) {
  475. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  476. if (!initialization) {
  477. this.stats.add("processed", "styleSheets", 1);
  478. }
  479. let stylesheetContent = styleElement.textContent;
  480. if (initialization) {
  481. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  482. stylesheetContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  483. } else {
  484. stylesheetContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  485. }
  486. styleElement.textContent = stylesheetContent;
  487. }));
  488. }
  489. async scripts() {
  490. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  491. if (scriptElement.src) {
  492. this.stats.add("processed", "scripts", 1);
  493. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  494. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  495. }
  496. scriptElement.removeAttribute("src");
  497. }));
  498. }
  499. async frames(initialization) {
  500. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  501. await Promise.all(frameElements.map(async frameElement => {
  502. DomProcessorHelper.setFrameEmptySrc(frameElement);
  503. frameElement.setAttribute("sandbox", "");
  504. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  505. if (frameWindowId) {
  506. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  507. if (frameData) {
  508. if (initialization) {
  509. const options = Object.create(this.options);
  510. options.insertSingleFileComment = false;
  511. options.insertFaviconLink = false;
  512. options.doc = null;
  513. options.win = null;
  514. options.url = frameData.baseURI;
  515. options.windowId = frameWindowId;
  516. if (frameData.content) {
  517. options.content = frameData.content;
  518. options.canvasData = frameData.canvasData;
  519. options.emptyStyleRulesText = frameData.emptyStyleRulesText;
  520. frameData.processor = new PageProcessor(options);
  521. frameData.frameElement = frameElement;
  522. await frameData.processor.loadPage();
  523. return frameData.processor.initialize();
  524. }
  525. } else {
  526. if (frameData.processor) {
  527. this.stats.add("processed", "frames", 1);
  528. await frameData.processor.preparePageData();
  529. const pageData = await frameData.processor.getPageData();
  530. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  531. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  532. this.stats.addAll(pageData);
  533. } else {
  534. this.stats.add("discarded", "frames", 1);
  535. }
  536. }
  537. }
  538. }
  539. }));
  540. }
  541. async htmlImports(initialization) {
  542. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  543. if (!this.relImportProcessors) {
  544. this.relImportProcessors = new Map();
  545. }
  546. await Promise.all(linkElements.map(async linkElement => {
  547. if (initialization) {
  548. const resourceURL = linkElement.href;
  549. const options = Object.create(this.options);
  550. options.insertSingleFileComment = false;
  551. options.insertFaviconLink = false;
  552. options.doc = null;
  553. options.win = null;
  554. options.url = resourceURL;
  555. if (resourceURL) {
  556. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  557. const processor = new PageProcessor(options);
  558. this.relImportProcessors.set(linkElement, processor);
  559. await processor.loadPage();
  560. return processor.initialize();
  561. }
  562. }
  563. } else {
  564. linkElement.setAttribute("href", EMPTY_DATA_URI);
  565. const processor = this.relImportProcessors.get(linkElement);
  566. if (processor) {
  567. this.stats.add("processed", "imports", 1);
  568. this.relImportProcessors.delete(linkElement);
  569. const pageData = await processor.getPageData();
  570. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  571. this.stats.addAll(pageData);
  572. } else {
  573. this.stats.add("discarded", "imports", 1);
  574. }
  575. }
  576. }));
  577. }
  578. async attributeStyles(initialization) {
  579. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  580. let stylesheetContent = element.getAttribute("style");
  581. if (initialization) {
  582. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  583. } else {
  584. stylesheetContent = await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  585. }
  586. element.setAttribute("style", stylesheetContent);
  587. }));
  588. }
  589. async linkStylesheets() {
  590. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  591. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  592. const styleElement = this.doc.createElement("style");
  593. styleElement.textContent = stylesheetContent;
  594. linkElement.parentElement.replaceChild(styleElement, linkElement);
  595. }));
  596. }
  597. }
  598. // ---------
  599. // DomHelper
  600. // ---------
  601. class DomProcessorHelper {
  602. static setFrameEmptySrc(frameElement) {
  603. if (frameElement.tagName == "OBJECT") {
  604. frameElement.setAttribute("data", "data:text/html,");
  605. } else {
  606. frameElement.setAttribute("srcdoc", "");
  607. frameElement.removeAttribute("src");
  608. }
  609. }
  610. static setFrameContent(frameElement, content) {
  611. if (frameElement.tagName == "OBJECT") {
  612. frameElement.setAttribute("data", "data:text/html," + content);
  613. } else {
  614. frameElement.setAttribute("srcdoc", content);
  615. frameElement.removeAttribute("src");
  616. }
  617. }
  618. static isolateElements(rootElement) {
  619. rootElement.querySelectorAll("*").forEach(element => {
  620. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  621. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  622. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  623. element.remove();
  624. }
  625. });
  626. isolateParentElements(rootElement.parentElement, rootElement);
  627. function isolateParentElements(parentElement, element) {
  628. if (parentElement) {
  629. Array.from(parentElement.childNodes).forEach(node => {
  630. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  631. node.remove();
  632. }
  633. });
  634. }
  635. element = element.parentElement;
  636. if (element && element.parentElement) {
  637. isolateParentElements(element.parentElement, element);
  638. }
  639. }
  640. }
  641. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  642. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  643. const imports = DomUtil.getImportFunctions(stylesheetContent);
  644. await Promise.all(imports.map(async cssImport => {
  645. const match = DomUtil.matchImport(cssImport);
  646. if (match) {
  647. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  648. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  649. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  650. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  651. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  652. if (stylesheetContent.indexOf(cssImport) != -1) {
  653. importedStylesheetContent = DomProcessorHelper.resolveStylesheetURLs(importedStylesheetContent, styleSheetUrl);
  654. DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  655. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  656. }
  657. }
  658. }
  659. }));
  660. return stylesheetContent;
  661. }
  662. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  663. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  664. urlFunctions.map(urlFunction => {
  665. let resourceURL = DomUtil.matchURL(urlFunction);
  666. resourceURL = DomUtil.normalizeURL(resourceURL);
  667. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  668. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  669. } else {
  670. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  671. const escapedResourceURL = resourceURL.replace(/&/g, "&amp;").replace(/\u00a0/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  672. if (escapedResourceURL != resourceURL) {
  673. stylesheetContent = stylesheetContent.replace(resourceURL, escapedResourceURL);
  674. }
  675. }
  676. }
  677. });
  678. return stylesheetContent;
  679. }
  680. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  681. resourceURL = DomUtil.normalizeURL(resourceURL);
  682. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  683. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  684. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, resourceURL);
  685. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  686. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  687. return stylesheetContent;
  688. }
  689. }
  690. static async processStylesheet(stylesheetContent, baseURI) {
  691. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  692. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  693. await Promise.all(urlFunctions.map(async urlFunction => {
  694. let resourceURL = DomUtil.matchURL(urlFunction);
  695. resourceURL = DomUtil.normalizeURL(resourceURL);
  696. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  697. const dataURI = await batchRequest.addURL(resourceURL);
  698. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  699. }
  700. }));
  701. return stylesheetContent;
  702. }
  703. static async processAttribute(resourceElements, attributeName, baseURI) {
  704. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  705. let resourceURL = resourceElement.getAttribute(attributeName);
  706. if (resourceURL) {
  707. resourceURL = DomUtil.normalizeURL(resourceURL);
  708. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  709. try {
  710. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  711. resourceElement.setAttribute(attributeName, dataURI);
  712. } catch (error) {
  713. /* ignored */
  714. }
  715. }
  716. }
  717. }));
  718. }
  719. static async processSrcset(resourceElements, attributeName, baseURI) {
  720. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  721. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  722. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  723. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  724. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  725. try {
  726. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  727. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  728. } catch (error) {
  729. /* ignored */
  730. }
  731. }
  732. }));
  733. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  734. }));
  735. }
  736. }
  737. // -------
  738. // DomUtil
  739. // -------
  740. const DATA_URI_PREFIX = "data:";
  741. const BLOB_URI_PREFIX = "blob:";
  742. const ABOUT_BLANK_URI = "about:blank";
  743. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  744. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  745. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  746. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  747. 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;
  748. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  749. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  750. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  751. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  752. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  753. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  754. class DomUtil {
  755. static normalizeURL(url) {
  756. if (url.startsWith(DATA_URI_PREFIX)) {
  757. return url;
  758. } else {
  759. return url.split("#")[0];
  760. }
  761. }
  762. static getUrlFunctions(stylesheetContent) {
  763. return stylesheetContent.match(REGEXP_URL_FN) || [];
  764. }
  765. static getImportFunctions(stylesheetContent) {
  766. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  767. }
  768. static matchURL(stylesheetContent) {
  769. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  770. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  771. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  772. return match && match[1];
  773. }
  774. static testValidPath(resourceURL) {
  775. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  776. }
  777. static matchImport(stylesheetContent) {
  778. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  779. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  780. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  781. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  782. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  783. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  784. if (match) {
  785. const [, resourceURL, media] = match;
  786. return { resourceURL, media };
  787. }
  788. }
  789. static removeCssComments(stylesheetContent) {
  790. let start, end;
  791. do {
  792. start = stylesheetContent.indexOf("/*");
  793. end = stylesheetContent.indexOf("*/", start);
  794. if (start != -1 && end != -1) {
  795. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  796. }
  797. } while (start != -1 && end != -1);
  798. return stylesheetContent;
  799. }
  800. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  801. if (mediaQuery) {
  802. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  803. } else {
  804. return stylesheetContent;
  805. }
  806. }
  807. }
  808. // -----
  809. // Stats
  810. // -----
  811. const STATS_DEFAULT_VALUES = {
  812. discarded: {
  813. htmlBytes: 0,
  814. hiddenElements: 0,
  815. imports: 0,
  816. scripts: 0,
  817. objects: 0,
  818. audioSource: 0,
  819. videoSource: 0,
  820. frames: 0,
  821. cssRules: 0
  822. },
  823. processed: {
  824. htmlBytes: 0,
  825. imports: 0,
  826. scripts: 0,
  827. frames: 0,
  828. cssRules: 0,
  829. canvas: 0,
  830. styleSheets: 0,
  831. resources: 0
  832. }
  833. };
  834. class Stats {
  835. constructor(options) {
  836. this.options = options;
  837. if (options.displayStats) {
  838. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  839. }
  840. }
  841. set(type, subType, value) {
  842. if (this.options.displayStats) {
  843. this.data[type][subType] = value;
  844. }
  845. }
  846. add(type, subType, value) {
  847. if (this.options.displayStats) {
  848. this.data[type][subType] += value;
  849. }
  850. }
  851. addAll(pageData) {
  852. if (this.options.displayStats) {
  853. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  854. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  855. }
  856. }
  857. }
  858. return { getClass };
  859. })();