single-file-core.js 29 KB

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