single-file-core.js 34 KB

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