single-file-core.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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.stylesheetContents = docData.stylesheetContents;
  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.replaceStyleContents();
  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, asDataURI = true) {
  185. return new Promise((resolve, reject) => {
  186. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  187. const resourceRequests = this.requests.get(requestKey);
  188. if (resourceRequests) {
  189. resourceRequests.push({ resolve, reject });
  190. } else {
  191. this.requests.set(requestKey, [{ resolve, reject }]);
  192. }
  193. });
  194. }
  195. getMaxResources() {
  196. return Array.from(this.requests.keys()).length;
  197. }
  198. async run(onloadListener, options) {
  199. const resourceURLs = Array.from(this.requests.keys());
  200. let indexResource = 0;
  201. return Promise.all(resourceURLs.map(async requestKey => {
  202. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  203. const resourceRequests = this.requests.get(requestKey);
  204. try {
  205. const dataURI = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  206. indexResource = indexResource + 1;
  207. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  208. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  209. } catch (error) {
  210. indexResource = indexResource + 1;
  211. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  212. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  213. }
  214. this.requests.delete(requestKey);
  215. }));
  216. }
  217. }
  218. // ------------
  219. // DOMProcessor
  220. // ------------
  221. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  222. const EMPTY_DATA_URI = "data:base64,";
  223. const batchRequest = new BatchRequest();
  224. class DOMProcessor {
  225. constructor(options) {
  226. this.options = options;
  227. this.stats = new Stats(options);
  228. this.baseURI = DomUtil.normalizeURL(options.url);
  229. }
  230. async loadPage(pageContent) {
  231. if (!pageContent || this.options.saveRawPage) {
  232. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  233. }
  234. this.doc = DOM.createDoc(pageContent, this.baseURI);
  235. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  236. await DOMProcessor.loadEscapedFragmentPage();
  237. }
  238. }
  239. async loadEscapedFragmentPage() {
  240. if (this.baseURI.includes("?")) {
  241. this.baseURI += "&";
  242. } else {
  243. this.baseURI += "?";
  244. }
  245. this.baseURI += ESCAPED_FRAGMENT;
  246. await this.loadPage();
  247. }
  248. async retrieveResources(onloadListener) {
  249. this.stats.set("processed", "resources", batchRequest.getMaxResources());
  250. await batchRequest.run(onloadListener, this.options);
  251. }
  252. getPageData() {
  253. DOM.postProcessDoc(this.doc, this.options);
  254. if (this.options.selected) {
  255. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  256. if (rootElement) {
  257. DomProcessorHelper.isolateElements(rootElement);
  258. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  259. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  260. }
  261. }
  262. const titleElement = this.doc.querySelector("title");
  263. let title;
  264. if (titleElement) {
  265. title = titleElement.textContent.trim();
  266. }
  267. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  268. const url = new URL(this.baseURI);
  269. let size;
  270. if (this.options.displayStats) {
  271. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  272. }
  273. const content = DOM.serialize(this.doc, this.options.compressHTML);
  274. if (this.options.displayStats) {
  275. const contentSize = DOM.getContentSize(content);
  276. this.stats.set("processed", "htmlBytes", contentSize);
  277. this.stats.add("discarded", "htmlBytes", size - contentSize);
  278. }
  279. return {
  280. stats: this.stats.data,
  281. title: title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "Untitled page")),
  282. content
  283. };
  284. }
  285. insertNoscriptContents() {
  286. const DOMParser = DOM.getParser();
  287. if (DOMParser) {
  288. this.doc.querySelectorAll("noscript").forEach(element => {
  289. const fragment = this.doc.createDocumentFragment();
  290. Array.from(element.childNodes).forEach(node => {
  291. const parsedNode = new DOMParser().parseFromString(node.nodeValue, "text/html");
  292. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  293. this.doc.importNode(node);
  294. fragment.appendChild(node);
  295. });
  296. });
  297. element.parentElement.replaceChild(fragment, element);
  298. });
  299. }
  300. }
  301. lazyLoadImages() {
  302. DOM.lazyLoader(this.doc);
  303. }
  304. removeDiscardedResources() {
  305. 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\"])");
  306. this.stats.set("discarded", "objects", objectElements.length);
  307. objectElements.forEach(element => element.remove());
  308. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  309. replacedAttributeValue.forEach(element => element.setAttribute("rel", element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "")));
  310. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  311. this.doc.querySelectorAll("[onerror]").forEach(element => element.removeAttribute("onerror"));
  312. if (this.options.removeAudioSrc) {
  313. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  314. this.stats.set("discarded", "audioSource", audioSourceElements.length);
  315. audioSourceElements.forEach(element => element.removeAttribute("src"));
  316. }
  317. if (this.options.removeVideoSrc) {
  318. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  319. this.stats.set("discarded", "videoSource", videoSourceElements.length);
  320. videoSourceElements.forEach(element => element.removeAttribute("src"));
  321. }
  322. }
  323. removeDefaultHeadTags() {
  324. this.doc.querySelectorAll("base").forEach(element => element.remove());
  325. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  326. this.doc.head.querySelector("meta[charset]").remove();
  327. }
  328. }
  329. removeUIElements() {
  330. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  331. }
  332. removeScripts() {
  333. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  334. this.stats.set("discarded", "scripts", scriptElements.length);
  335. scriptElements.forEach(element => element.remove());
  336. }
  337. removeFrames() {
  338. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  339. this.stats.set("discarded", "frames", frameElements.length);
  340. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  341. }
  342. removeImports() {
  343. const importElements = this.doc.querySelectorAll("link[rel=import]");
  344. this.stats.set("discarded", "imports", importElements.length);
  345. importElements.forEach(element => element.remove());
  346. }
  347. resetCharsetMeta() {
  348. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => element.remove());
  349. const metaElement = this.doc.createElement("meta");
  350. metaElement.setAttribute("charset", "utf-8");
  351. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  352. }
  353. insertFaviconLink() {
  354. let faviconElement = this.doc.querySelector("link[href][rel*=\"icon\"]");
  355. if (!faviconElement) {
  356. faviconElement = this.doc.createElement("link");
  357. faviconElement.setAttribute("type", "image/x-icon");
  358. faviconElement.setAttribute("rel", "shortcut icon");
  359. faviconElement.setAttribute("href", "/favicon.ico");
  360. }
  361. this.doc.head.appendChild(faviconElement);
  362. }
  363. resolveHrefs() {
  364. this.doc.querySelectorAll("[href]").forEach(element => {
  365. const match = element.href && element.href.match(/(.*)#.*$/);
  366. if (!match || match[1] != this.baseURI) {
  367. element.setAttribute("href", element.href);
  368. }
  369. });
  370. }
  371. removeUnusedStyles() {
  372. const stats = DOM.cssMinifier(this.doc);
  373. this.stats.set("processed", "cssRules", stats.processed);
  374. this.stats.set("discarded", "cssRules", stats.discarded);
  375. }
  376. removeAlternativeFonts(secondPass) {
  377. DOM.fontsMinifier(this.doc, secondPass);
  378. }
  379. removeHiddenElements(sessionId) {
  380. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(sessionId) + "]");
  381. this.stats.set("discarded", "hiddenElements", hiddenElements.length);
  382. hiddenElements.forEach(element => element.remove());
  383. }
  384. compressHTML(postProcess) {
  385. if (postProcess) {
  386. let size;
  387. if (this.options.displayStats) {
  388. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  389. }
  390. DOM.htmlminiPostProcess(this.doc);
  391. if (this.options.displayStats) {
  392. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  393. }
  394. } else {
  395. let size;
  396. if (this.options.displayStats) {
  397. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  398. }
  399. DOM.htmlminiProcess(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  400. if (this.options.displayStats) {
  401. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  402. }
  403. }
  404. }
  405. compressCSS() {
  406. this.doc.querySelectorAll("style").forEach(styleElement => {
  407. if (styleElement) {
  408. styleElement.textContent = DOM.uglifycss(styleElement.textContent);
  409. }
  410. });
  411. this.doc.querySelectorAll("[style]").forEach(element => {
  412. element.setAttribute("style", DOM.uglifycss(element.getAttribute("style")));
  413. });
  414. }
  415. insertSingleFileCommentNode() {
  416. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  417. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  418. }
  419. replaceCanvasElements() {
  420. if (this.options.canvasData) {
  421. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  422. const canvasData = this.options.canvasData[indexCanvasElement];
  423. if (canvasData) {
  424. const imgElement = this.doc.createElement("img");
  425. imgElement.setAttribute("src", canvasData.dataURI);
  426. Array.from(canvasElement.attributes).forEach(attribute => {
  427. if (attribute.value) {
  428. imgElement.setAttribute(attribute.name, attribute.value);
  429. }
  430. });
  431. if (!imgElement.width && canvasData.width) {
  432. imgElement.style.pixelWidth = canvasData.width;
  433. }
  434. if (!imgElement.height && canvasData.height) {
  435. imgElement.style.pixelHeight = canvasData.height;
  436. }
  437. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  438. this.stats.add("processed", "canvas", 1);
  439. }
  440. });
  441. }
  442. }
  443. replaceStyleContents() {
  444. if (this.options.stylesheetContents) {
  445. let indexStyle = 0;
  446. this.doc.querySelectorAll("style").forEach(styleElement => {
  447. styleElement.textContent = this.options.stylesheetContents[indexStyle];
  448. indexStyle++;
  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"), "xlink:href", this.baseURI),
  459. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI),
  460. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI)
  461. ];
  462. if (!this.options.removeAudioSrc) {
  463. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  464. }
  465. if (!this.options.removeVideoSrc) {
  466. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  467. }
  468. if (this.options.lazyLoadImages) {
  469. const imageSelectors = DOM.lazyLoaderImageSelectors();
  470. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  471. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI)));
  472. }
  473. await resourcePromises;
  474. }
  475. async inlineStylesheets(initialization) {
  476. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  477. if (!initialization) {
  478. this.stats.add("processed", "styleSheets", 1);
  479. }
  480. let stylesheetContent = styleElement.textContent;
  481. if (initialization) {
  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.stylesheetContents = frameData.stylesheetContents;
  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 = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  643. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  644. const imports = DomUtil.getImportFunctions(stylesheetContent);
  645. await Promise.all(imports.map(async cssImport => {
  646. const match = DomUtil.matchImport(cssImport);
  647. if (match) {
  648. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  649. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  650. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  651. let importedStylesheetContent = await Download.getContent(styleSheetUrl, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  652. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  653. if (stylesheetContent.includes(cssImport)) {
  654. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  655. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(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. const resolvedURL = new URL(resourceURL, baseURI).href;
  669. if (resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  670. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(resourceURL, resolvedURL));
  671. }
  672. } else {
  673. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  674. const escapedResourceURL = resourceURL.replace(/&/g, "&amp;").replace(/\u00a0/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  675. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  676. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(resourceURL, escapedResourceURL));
  677. }
  678. }
  679. }
  680. });
  681. return stylesheetContent;
  682. }
  683. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  684. resourceURL = DomUtil.normalizeURL(resourceURL);
  685. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  686. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  687. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  688. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  689. return stylesheetContent;
  690. }
  691. }
  692. static async processStylesheet(stylesheetContent, baseURI) {
  693. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  694. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  695. await Promise.all(urlFunctions.map(async urlFunction => {
  696. let resourceURL = DomUtil.matchURL(urlFunction);
  697. resourceURL = DomUtil.normalizeURL(resourceURL);
  698. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && stylesheetContent.includes(urlFunction)) {
  699. const dataURI = await batchRequest.addURL(resourceURL);
  700. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(resourceURL, dataURI));
  701. }
  702. }));
  703. return stylesheetContent;
  704. }
  705. static async processAttribute(resourceElements, attributeName, baseURI) {
  706. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  707. let resourceURL = resourceElement.getAttribute(attributeName);
  708. if (resourceURL) {
  709. resourceURL = DomUtil.normalizeURL(resourceURL);
  710. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  711. try {
  712. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  713. resourceElement.setAttribute(attributeName, dataURI);
  714. } catch (error) {
  715. /* ignored */
  716. }
  717. }
  718. }
  719. }));
  720. }
  721. static async processXLinks(resourceElements, baseURI) {
  722. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  723. const originalResourceURL = resourceElement.getAttribute("xlink:href");
  724. if (originalResourceURL) {
  725. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  726. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  727. try {
  728. const content = await batchRequest.addURL(new URL(resourceURL, baseURI).href, false);
  729. const DOMParser = DOM.getParser();
  730. if (DOMParser) {
  731. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  732. const hashMatch = originalResourceURL.match(/(#.+?)$/);
  733. if (hashMatch && hashMatch[0]) {
  734. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  735. if (symbolElement) {
  736. resourceElement.setAttribute("xlink:href", hashMatch[0]);
  737. resourceElement.parentElement.appendChild(symbolElement);
  738. }
  739. } else {
  740. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  741. }
  742. } else {
  743. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  744. }
  745. } catch (error) {
  746. /* ignored */
  747. }
  748. }
  749. }
  750. }));
  751. }
  752. static async processSrcset(resourceElements, attributeName, baseURI) {
  753. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  754. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  755. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  756. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  757. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  758. try {
  759. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  760. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  761. } catch (error) {
  762. /* ignored */
  763. }
  764. }
  765. }));
  766. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  767. }));
  768. }
  769. }
  770. // -------
  771. // DomUtil
  772. // -------
  773. const DATA_URI_PREFIX = "data:";
  774. const BLOB_URI_PREFIX = "blob:";
  775. const HTTP_URI_PREFIX = /^https?:\/\//;
  776. const ABOUT_BLANK_URI = "about:blank";
  777. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  778. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  779. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  780. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  781. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  782. 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;
  783. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  784. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  785. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  786. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  787. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  788. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  789. class DomUtil {
  790. static normalizeURL(url) {
  791. if (url.startsWith(DATA_URI_PREFIX)) {
  792. return url;
  793. } else {
  794. return url.split("#")[0];
  795. }
  796. }
  797. static getRegExp(string) {
  798. return new RegExp(string.replace(/([{}()^$&.*?/+|[\\\\]|\]|-)/g, "\\$1"), "gi");
  799. }
  800. static getUrlFunctions(stylesheetContent) {
  801. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  802. }
  803. static getImportFunctions(stylesheetContent) {
  804. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  805. }
  806. static matchURL(stylesheetContent) {
  807. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  808. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  809. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  810. return match && match[1];
  811. }
  812. static testValidPath(resourceURL) {
  813. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI && (!resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(NOT_EMPTY_URL));
  814. }
  815. static matchImport(stylesheetContent) {
  816. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  817. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  818. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  819. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  820. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  821. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  822. if (match) {
  823. const [, resourceURL, media] = match;
  824. return { resourceURL, media };
  825. }
  826. }
  827. static removeCssComments(stylesheetContent) {
  828. let start, end;
  829. do {
  830. start = stylesheetContent.indexOf("/*");
  831. end = stylesheetContent.indexOf("*/", start);
  832. if (start != -1 && end != -1) {
  833. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  834. }
  835. } while (start != -1 && end != -1);
  836. return stylesheetContent;
  837. }
  838. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  839. if (mediaQuery) {
  840. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  841. } else {
  842. return stylesheetContent;
  843. }
  844. }
  845. }
  846. // -----
  847. // Stats
  848. // -----
  849. const STATS_DEFAULT_VALUES = {
  850. discarded: {
  851. htmlBytes: 0,
  852. hiddenElements: 0,
  853. imports: 0,
  854. scripts: 0,
  855. objects: 0,
  856. audioSource: 0,
  857. videoSource: 0,
  858. frames: 0,
  859. cssRules: 0
  860. },
  861. processed: {
  862. htmlBytes: 0,
  863. imports: 0,
  864. scripts: 0,
  865. frames: 0,
  866. cssRules: 0,
  867. canvas: 0,
  868. styleSheets: 0,
  869. resources: 0
  870. }
  871. };
  872. class Stats {
  873. constructor(options) {
  874. this.options = options;
  875. if (options.displayStats) {
  876. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  877. }
  878. }
  879. set(type, subType, value) {
  880. if (this.options.displayStats) {
  881. this.data[type][subType] = value;
  882. }
  883. }
  884. add(type, subType, value) {
  885. if (this.options.displayStats) {
  886. this.data[type][subType] += value;
  887. }
  888. }
  889. addAll(pageData) {
  890. if (this.options.displayStats) {
  891. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  892. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  893. }
  894. }
  895. }
  896. return { getClass };
  897. })();