single-file-core.js 33 KB

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