single-file-core.js 37 KB

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