single-file-core.js 34 KB

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