single-file-core.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. this.SingleFileCore = this.SingleFileCore || (() => {
  21. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  23. let Download, DOM, URL, sessionId = 0;
  24. function getClass(...args) {
  25. [Download, DOM, URL] = args;
  26. return class {
  27. constructor(options) {
  28. this.options = options;
  29. options.sessionId = sessionId;
  30. sessionId++;
  31. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  32. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  33. }
  34. async initialize() {
  35. this.processor = new PageProcessor(this.options);
  36. await this.processor.loadPage();
  37. await this.processor.initialize();
  38. }
  39. async preparePageData() {
  40. await this.processor.preparePageData();
  41. }
  42. getPageData() {
  43. return this.processor.getPageData();
  44. }
  45. };
  46. }
  47. // -------------
  48. // ProgressEvent
  49. // -------------
  50. const PAGE_LOADING = "page-loading";
  51. const PAGE_LOADED = "page-loaded";
  52. const RESOURCES_INITIALIZING = "resource-initializing";
  53. const RESOURCES_INITIALIZED = "resources-initialized";
  54. const RESOURCE_LOADED = "resource-loaded";
  55. const PAGE_ENDED = "page-ended";
  56. class ProgressEvent {
  57. constructor(type, details) {
  58. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  59. }
  60. }
  61. // -------------
  62. // PageProcessor
  63. // -------------
  64. const STAGES = [{
  65. sync: [
  66. { action: "removeUIElements" },
  67. { action: "replaceStyleContents" },
  68. { option: "removeSrcSet", action: "removeSrcSet" },
  69. { option: "removeFrames", action: "removeFrames" },
  70. { option: "removeImports", action: "removeImports" },
  71. { option: "removeScripts", action: "removeScripts" },
  72. { action: "removeDiscardedResources" },
  73. { action: "resetCharsetMeta" },
  74. { option: "compressHTML", action: "compressHTML" },
  75. { option: "insertFaviconLink", action: "insertFaviconLink" },
  76. { action: "resolveHrefs" },
  77. { action: "replaceCanvasElements" },
  78. { option: "removeHiddenElements", action: "removeHiddenElements" }
  79. ],
  80. async: [
  81. { action: "inlineStylesheets" },
  82. { action: "linkStylesheets" },
  83. { action: "attributeStyles" },
  84. { option: "!removeFrames", action: "frames" },
  85. { option: "!removeImports", action: "htmlImports" }
  86. ]
  87. }, {
  88. sync: [
  89. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  90. { option: "compressHTML", action: "compressHTML" },
  91. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  92. { option: "compressCSS", action: "compressCSS" },
  93. ],
  94. async: [
  95. { action: "inlineStylesheets" },
  96. { action: "attributeStyles" },
  97. { action: "pageResources" },
  98. { option: "!removeScripts", action: "scripts" }
  99. ]
  100. }, {
  101. sync: [
  102. { option: "lazyLoadImages", action: "lazyLoadImages" },
  103. { option: "removeAlternativeFonts", action: "postRemoveAlternativeFonts" }
  104. ],
  105. async: [
  106. { option: "!removeFrames", action: "frames" },
  107. { option: "!removeImports", action: "htmlImports" },
  108. ]
  109. }, {
  110. sync: [
  111. { option: "compressHTML", action: "postCompressHTML" },
  112. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  113. { action: "removeDefaultHeadTags" }
  114. ]
  115. }];
  116. class PageProcessor {
  117. constructor(options) {
  118. this.options = options;
  119. this.options.url = this.options.url || this.options.doc.location.href;
  120. this.processor = new DOMProcessor(options);
  121. if (this.options.doc) {
  122. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  123. this.options.canvasData = docData.canvasData;
  124. this.options.stylesheetContents = docData.stylesheetContents;
  125. this.options.currentSrcImages = docData.currentSrcImages;
  126. }
  127. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  128. this.onprogress = options.onprogress || (() => { });
  129. }
  130. async loadPage() {
  131. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  132. await this.processor.loadPage(this.options.content);
  133. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  134. }
  135. async initialize() {
  136. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  137. await this.executeStage(0);
  138. this.pendingPromises = this.executeStage(1);
  139. if (this.options.doc) {
  140. DOM.postProcessDoc(this.options.doc, this.options);
  141. this.options.doc = null;
  142. this.options.win = null;
  143. }
  144. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  145. }
  146. async preparePageData() {
  147. if (!this.options.windowId) {
  148. await this.processor.retrieveResources(
  149. details => {
  150. details.pageURL = this.options.url;
  151. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  152. });
  153. }
  154. await this.pendingPromises;
  155. await this.executeStage(2);
  156. await this.executeStage(3);
  157. }
  158. getPageData() {
  159. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  160. return this.processor.getPageData();
  161. }
  162. async executeStage(step) {
  163. STAGES[step].sync.forEach(task => this.executeTask(task, !step));
  164. if (STAGES[step].async) {
  165. return Promise.all(STAGES[step].async.map(task => this.executeTask(task, !step)));
  166. }
  167. }
  168. executeTask(task, initialization) {
  169. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  170. return this.processor[task.action](initialization);
  171. }
  172. }
  173. }
  174. // --------
  175. // BatchRequest
  176. // --------
  177. class BatchRequest {
  178. constructor() {
  179. this.requests = new Map();
  180. }
  181. async addURL(resourceURL, asDataURI = true) {
  182. return new Promise((resolve, reject) => {
  183. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  184. const resourceRequests = this.requests.get(requestKey);
  185. if (resourceRequests) {
  186. resourceRequests.push({ resolve, reject });
  187. } else {
  188. this.requests.set(requestKey, [{ resolve, reject }]);
  189. }
  190. });
  191. }
  192. getMaxResources() {
  193. return Array.from(this.requests.keys()).length;
  194. }
  195. async run(onloadListener, options) {
  196. const resourceURLs = Array.from(this.requests.keys());
  197. let indexResource = 0;
  198. return Promise.all(resourceURLs.map(async requestKey => {
  199. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  200. const resourceRequests = this.requests.get(requestKey);
  201. try {
  202. const dataURI = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  203. indexResource = indexResource + 1;
  204. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  205. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  206. } catch (error) {
  207. indexResource = indexResource + 1;
  208. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  209. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  210. }
  211. this.requests.delete(requestKey);
  212. }));
  213. }
  214. }
  215. // ------------
  216. // DOMProcessor
  217. // ------------
  218. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  219. const EMPTY_DATA_URI = "data:base64,";
  220. const batchRequest = new BatchRequest();
  221. class DOMProcessor {
  222. constructor(options) {
  223. this.options = options;
  224. this.stats = new Stats(options);
  225. this.baseURI = DomUtil.normalizeURL(options.url);
  226. }
  227. async loadPage(pageContent) {
  228. if (!pageContent || this.options.saveRawPage) {
  229. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  230. }
  231. this.doc = DOM.createDoc(pageContent, this.baseURI);
  232. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  233. await DOMProcessor.loadEscapedFragmentPage();
  234. }
  235. }
  236. async loadEscapedFragmentPage() {
  237. if (this.baseURI.includes("?")) {
  238. this.baseURI += "&";
  239. } else {
  240. this.baseURI += "?";
  241. }
  242. this.baseURI += ESCAPED_FRAGMENT;
  243. await this.loadPage();
  244. }
  245. async retrieveResources(onloadListener) {
  246. this.stats.set("processed", "resources", batchRequest.getMaxResources());
  247. await batchRequest.run(onloadListener, this.options);
  248. }
  249. getPageData() {
  250. DOM.postProcessDoc(this.doc, this.options);
  251. if (this.options.selected) {
  252. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  253. if (rootElement) {
  254. DomProcessorHelper.isolateElements(rootElement);
  255. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  256. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  257. }
  258. }
  259. const titleElement = this.doc.querySelector("title");
  260. let title;
  261. if (titleElement) {
  262. title = titleElement.textContent.trim();
  263. }
  264. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  265. const url = new URL(this.baseURI);
  266. let size;
  267. if (this.options.displayStats) {
  268. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  269. }
  270. const content = DOM.serialize(this.doc, this.options.compressHTML);
  271. if (this.options.displayStats) {
  272. const contentSize = DOM.getContentSize(content);
  273. this.stats.set("processed", "htmlBytes", contentSize);
  274. this.stats.add("discarded", "htmlBytes", size - contentSize);
  275. }
  276. return {
  277. stats: this.stats.data,
  278. title: title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "Untitled page")),
  279. content
  280. };
  281. }
  282. lazyLoadImages() {
  283. DOM.lazyLoad(this.doc);
  284. }
  285. removeDiscardedResources() {
  286. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed:not([src*=\".svg\"])");
  287. this.stats.set("discarded", "objects", objectElements.length);
  288. objectElements.forEach(element => element.remove());
  289. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  290. replacedAttributeValue.forEach(element => element.setAttribute("rel", element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "")));
  291. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  292. this.doc.querySelectorAll("[onerror]").forEach(element => element.removeAttribute("onerror"));
  293. if (this.options.removeAudioSrc) {
  294. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  295. this.stats.set("discarded", "audioSource", audioSourceElements.length);
  296. audioSourceElements.forEach(element => element.removeAttribute("src"));
  297. }
  298. if (this.options.removeVideoSrc) {
  299. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  300. this.stats.set("discarded", "videoSource", videoSourceElements.length);
  301. videoSourceElements.forEach(element => element.removeAttribute("src"));
  302. }
  303. }
  304. removeDefaultHeadTags() {
  305. this.doc.querySelectorAll("base").forEach(element => element.remove());
  306. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  307. this.doc.head.querySelector("meta[charset]").remove();
  308. }
  309. }
  310. removeUIElements() {
  311. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  312. }
  313. removeScripts() {
  314. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  315. this.stats.set("discarded", "scripts", scriptElements.length);
  316. scriptElements.forEach(element => element.remove());
  317. }
  318. removeFrames() {
  319. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  320. this.stats.set("discarded", "frames", frameElements.length);
  321. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  322. }
  323. removeImports() {
  324. const importElements = this.doc.querySelectorAll("link[rel=import]");
  325. this.stats.set("discarded", "imports", importElements.length);
  326. importElements.forEach(element => element.remove());
  327. }
  328. resetCharsetMeta() {
  329. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => element.remove());
  330. const metaElement = this.doc.createElement("meta");
  331. metaElement.setAttribute("charset", "utf-8");
  332. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  333. }
  334. insertFaviconLink() {
  335. let faviconElement = this.doc.querySelector("link[href][rel*=\"icon\"]");
  336. if (!faviconElement) {
  337. faviconElement = this.doc.createElement("link");
  338. faviconElement.setAttribute("type", "image/x-icon");
  339. faviconElement.setAttribute("rel", "shortcut icon");
  340. faviconElement.setAttribute("href", "/favicon.ico");
  341. }
  342. this.doc.head.appendChild(faviconElement);
  343. }
  344. resolveHrefs() {
  345. this.doc.querySelectorAll("[href]").forEach(element => {
  346. if (element.href) {
  347. const href = element.href.baseVal ? element.href.baseVal : element.href;
  348. const match = href.match(/(.*)#.*$/);
  349. if (!match || match[1] != this.baseURI) {
  350. element.setAttribute("href", href);
  351. }
  352. }
  353. });
  354. }
  355. removeUnusedStyles() {
  356. const stats = DOM.minifyCSS(this.doc);
  357. this.stats.set("processed", "cssRules", stats.processed);
  358. this.stats.set("discarded", "cssRules", stats.discarded);
  359. }
  360. removeAlternativeFonts() {
  361. DOM.minifyFonts(this.doc);
  362. }
  363. removeSrcSet() {
  364. this.doc.querySelectorAll("[srcset], [data-srcset]").forEach((element, elementIndex) => {
  365. const tagName = element.tagName.toLowerCase();
  366. const currentSrcImage = this.options.currentSrcImages && this.options.currentSrcImages[elementIndex];
  367. if (tagName == "source") {
  368. const parentElement = element.parentElement;
  369. if (parentElement.tagName.toLowerCase() == "picture") {
  370. const imageElement = parentElement.querySelector("img");
  371. if (imageElement && (imageElement.src || currentSrcImage)) {
  372. element.remove();
  373. if (currentSrcImage) {
  374. imageElement.src = currentSrcImage;
  375. }
  376. }
  377. }
  378. }
  379. if (tagName == "img" && (element.src || currentSrcImage)) {
  380. element.removeAttribute("srcset");
  381. element.removeAttribute("sizes");
  382. if (currentSrcImage) {
  383. element.src = currentSrcImage;
  384. }
  385. }
  386. });
  387. }
  388. postRemoveAlternativeFonts() {
  389. DOM.minifyFonts(this.doc, true);
  390. if (this.options.compressCSS) {
  391. this.compressCSS();
  392. }
  393. }
  394. removeHiddenElements() {
  395. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  396. this.stats.set("discarded", "hiddenElements", hiddenElements.length);
  397. hiddenElements.forEach(element => element.remove());
  398. }
  399. compressHTML() {
  400. let size;
  401. if (this.options.displayStats) {
  402. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  403. }
  404. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  405. if (this.options.displayStats) {
  406. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  407. }
  408. }
  409. postCompressHTML() {
  410. let size;
  411. if (this.options.displayStats) {
  412. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  413. }
  414. DOM.postMinifyHTML(this.doc);
  415. if (this.options.displayStats) {
  416. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  417. }
  418. }
  419. compressCSS() {
  420. this.doc.querySelectorAll("style").forEach(styleElement => {
  421. if (styleElement) {
  422. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  423. }
  424. });
  425. this.doc.querySelectorAll("[style]").forEach(element => {
  426. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  427. });
  428. }
  429. insertSingleFileComment() {
  430. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  431. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  432. }
  433. replaceCanvasElements() {
  434. if (this.options.canvasData) {
  435. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  436. const canvasData = this.options.canvasData[indexCanvasElement];
  437. if (canvasData) {
  438. const imgElement = this.doc.createElement("img");
  439. imgElement.setAttribute("src", canvasData.dataURI);
  440. Array.from(canvasElement.attributes).forEach(attribute => {
  441. if (attribute.value) {
  442. imgElement.setAttribute(attribute.name, attribute.value);
  443. }
  444. });
  445. if (!imgElement.width && canvasData.width) {
  446. imgElement.style.pixelWidth = canvasData.width;
  447. }
  448. if (!imgElement.height && canvasData.height) {
  449. imgElement.style.pixelHeight = canvasData.height;
  450. }
  451. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  452. this.stats.add("processed", "canvas", 1);
  453. }
  454. });
  455. }
  456. }
  457. replaceStyleContents() {
  458. if (this.options.stylesheetContents) {
  459. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  460. if (this.options.stylesheetContents[styleIndex]) {
  461. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  462. }
  463. });
  464. }
  465. }
  466. async pageResources() {
  467. const resourcePromises = [
  468. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  469. 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),
  470. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  471. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  472. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image"), "xlink:href", this.baseURI),
  473. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI),
  474. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI)
  475. ];
  476. if (!this.options.removeAudioSrc) {
  477. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  478. }
  479. if (!this.options.removeVideoSrc) {
  480. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  481. }
  482. if (this.options.lazyLoadImages) {
  483. const imageSelectors = DOM.lazyLoaderImageSelectors();
  484. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  485. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI)));
  486. }
  487. await resourcePromises;
  488. }
  489. async inlineStylesheets(initialization) {
  490. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  491. if (!initialization) {
  492. this.stats.add("processed", "styleSheets", 1);
  493. }
  494. let stylesheetContent = styleElement.textContent;
  495. if (initialization) {
  496. stylesheetContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  497. } else {
  498. stylesheetContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  499. }
  500. styleElement.textContent = stylesheetContent;
  501. }));
  502. }
  503. async scripts() {
  504. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  505. if (scriptElement.src) {
  506. this.stats.add("processed", "scripts", 1);
  507. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  508. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  509. }
  510. scriptElement.removeAttribute("src");
  511. }));
  512. }
  513. async frames(initialization) {
  514. if (this.options.framesData) {
  515. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  516. await Promise.all(frameElements.map(async frameElement => {
  517. DomProcessorHelper.setFrameEmptySrc(frameElement);
  518. frameElement.setAttribute("sandbox", "");
  519. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  520. if (frameWindowId) {
  521. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  522. if (frameData) {
  523. if (initialization) {
  524. const options = Object.create(this.options);
  525. options.insertSingleFileComment = false;
  526. options.insertFaviconLink = false;
  527. options.doc = null;
  528. options.win = null;
  529. options.url = frameData.baseURI;
  530. options.windowId = frameWindowId;
  531. if (frameData.content) {
  532. options.content = frameData.content;
  533. options.canvasData = frameData.canvasData;
  534. options.stylesheetContents = frameData.stylesheetContents;
  535. options.currentSrcImages = frameData.currentSrcImages;
  536. frameData.processor = new PageProcessor(options);
  537. frameData.frameElement = frameElement;
  538. await frameData.processor.loadPage();
  539. return frameData.processor.initialize();
  540. }
  541. } else {
  542. if (frameData.processor) {
  543. this.stats.add("processed", "frames", 1);
  544. await frameData.processor.preparePageData();
  545. const pageData = await frameData.processor.getPageData();
  546. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  547. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  548. this.stats.addAll(pageData);
  549. } else {
  550. this.stats.add("discarded", "frames", 1);
  551. }
  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. this.stats.add("processed", "imports", 1);
  585. this.relImportProcessors.delete(linkElement);
  586. const pageData = await processor.getPageData();
  587. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  588. this.stats.addAll(pageData);
  589. } else {
  590. this.stats.add("discarded", "imports", 1);
  591. }
  592. }
  593. }));
  594. }
  595. async attributeStyles(initialization) {
  596. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  597. let stylesheetContent = element.getAttribute("style");
  598. if (initialization) {
  599. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  600. } else {
  601. stylesheetContent = await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  602. }
  603. element.setAttribute("style", 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 = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  660. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  661. const imports = DomUtil.getImportFunctions(stylesheetContent);
  662. await Promise.all(imports.map(async cssImport => {
  663. const match = DomUtil.matchImport(cssImport);
  664. if (match) {
  665. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  666. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  667. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  668. let importedStylesheetContent = await Download.getContent(styleSheetUrl, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  669. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  670. if (stylesheetContent.includes(cssImport)) {
  671. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  672. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  673. }
  674. }
  675. }
  676. }));
  677. return stylesheetContent;
  678. }
  679. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  680. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  681. urlFunctions.map(urlFunction => {
  682. const originalResourceURL = DomUtil.matchURL(urlFunction);
  683. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  684. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  685. const resolvedURL = new URL(resourceURL, baseURI).href;
  686. if (resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  687. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  688. }
  689. } else {
  690. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  691. const escapedResourceURL = resourceURL.replace(/&/g, "&amp;").replace(/\u00a0/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  692. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  693. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  694. }
  695. }
  696. }
  697. });
  698. return stylesheetContent;
  699. }
  700. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  701. resourceURL = DomUtil.normalizeURL(resourceURL);
  702. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  703. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  704. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  705. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  706. return stylesheetContent;
  707. }
  708. }
  709. static async processStylesheet(stylesheetContent, baseURI) {
  710. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  711. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  712. await Promise.all(urlFunctions.map(async urlFunction => {
  713. const originalResourceURL = DomUtil.matchURL(urlFunction);
  714. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  715. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && stylesheetContent.includes(urlFunction)) {
  716. const dataURI = await batchRequest.addURL(resourceURL);
  717. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, dataURI));
  718. }
  719. }));
  720. return stylesheetContent;
  721. }
  722. static async processAttribute(resourceElements, attributeName, baseURI) {
  723. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  724. let resourceURL = resourceElement.getAttribute(attributeName);
  725. if (resourceURL) {
  726. resourceURL = DomUtil.normalizeURL(resourceURL);
  727. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  728. try {
  729. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  730. resourceElement.setAttribute(attributeName, dataURI);
  731. } catch (error) {
  732. /* ignored */
  733. }
  734. }
  735. }
  736. }));
  737. }
  738. static async processXLinks(resourceElements, baseURI) {
  739. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  740. const originalResourceURL = resourceElement.getAttribute("xlink:href");
  741. if (originalResourceURL) {
  742. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  743. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  744. try {
  745. const content = await batchRequest.addURL(new URL(resourceURL, baseURI).href, false);
  746. const DOMParser = DOM.getParser();
  747. if (DOMParser) {
  748. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  749. const hashMatch = originalResourceURL.match(/(#.+?)$/);
  750. if (hashMatch && hashMatch[0]) {
  751. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  752. if (symbolElement) {
  753. resourceElement.setAttribute("xlink:href", hashMatch[0]);
  754. resourceElement.parentElement.appendChild(symbolElement);
  755. }
  756. } else {
  757. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  758. }
  759. } else {
  760. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  761. }
  762. } catch (error) {
  763. /* ignored */
  764. }
  765. }
  766. }
  767. }));
  768. }
  769. static async processSrcset(resourceElements, attributeName, baseURI) {
  770. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  771. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  772. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  773. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  774. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  775. try {
  776. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  777. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  778. } catch (error) {
  779. /* ignored */
  780. }
  781. }
  782. }));
  783. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  784. }));
  785. }
  786. }
  787. // -------
  788. // DomUtil
  789. // -------
  790. const DATA_URI_PREFIX = "data:";
  791. const BLOB_URI_PREFIX = "blob:";
  792. const HTTP_URI_PREFIX = /^https?:\/\//;
  793. const ABOUT_BLANK_URI = "about:blank";
  794. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  795. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  796. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  797. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  798. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  799. 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;
  800. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  801. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  802. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  803. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  804. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  805. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  806. class DomUtil {
  807. static normalizeURL(url) {
  808. if (url.startsWith(DATA_URI_PREFIX)) {
  809. return url;
  810. } else {
  811. return url.split("#")[0];
  812. }
  813. }
  814. static getRegExp(string) {
  815. return new RegExp(string.replace(/([{}()^$&.*?/+|[\\\\]|\]|-)/g, "\\$1"), "gi");
  816. }
  817. static getUrlFunctions(stylesheetContent) {
  818. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  819. }
  820. static getImportFunctions(stylesheetContent) {
  821. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  822. }
  823. static matchURL(stylesheetContent) {
  824. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  825. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  826. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  827. return match && match[1];
  828. }
  829. static testValidPath(resourceURL) {
  830. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI && (!resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(NOT_EMPTY_URL));
  831. }
  832. static matchImport(stylesheetContent) {
  833. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  834. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  835. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  836. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  837. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  838. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  839. if (match) {
  840. const [, resourceURL, media] = match;
  841. return { resourceURL, media };
  842. }
  843. }
  844. static removeCssComments(stylesheetContent) {
  845. let start, end;
  846. do {
  847. start = stylesheetContent.indexOf("/*");
  848. end = stylesheetContent.indexOf("*/", start);
  849. if (start != -1 && end != -1) {
  850. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  851. }
  852. } while (start != -1 && end != -1);
  853. return stylesheetContent;
  854. }
  855. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  856. if (mediaQuery) {
  857. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  858. } else {
  859. return stylesheetContent;
  860. }
  861. }
  862. }
  863. // -----
  864. // Stats
  865. // -----
  866. const STATS_DEFAULT_VALUES = {
  867. discarded: {
  868. htmlBytes: 0,
  869. hiddenElements: 0,
  870. imports: 0,
  871. scripts: 0,
  872. objects: 0,
  873. audioSource: 0,
  874. videoSource: 0,
  875. frames: 0,
  876. cssRules: 0
  877. },
  878. processed: {
  879. htmlBytes: 0,
  880. imports: 0,
  881. scripts: 0,
  882. frames: 0,
  883. cssRules: 0,
  884. canvas: 0,
  885. styleSheets: 0,
  886. resources: 0
  887. }
  888. };
  889. class Stats {
  890. constructor(options) {
  891. this.options = options;
  892. if (options.displayStats) {
  893. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  894. }
  895. }
  896. set(type, subType, value) {
  897. if (this.options.displayStats) {
  898. this.data[type][subType] = value;
  899. }
  900. }
  901. add(type, subType, value) {
  902. if (this.options.displayStats) {
  903. this.data[type][subType] += value;
  904. }
  905. }
  906. addAll(pageData) {
  907. if (this.options.displayStats) {
  908. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  909. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  910. }
  911. }
  912. }
  913. return { getClass };
  914. })();