single-file-core.js 37 KB

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