single-file-core.js 34 KB

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