single-file-core.js 37 KB

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