single-file-core.js 29 KB

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