1
0

single-file-core.js 34 KB

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