single-file-core.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  386. await Promise.all(frameElements.map(async (frameElement, frameIndex) => {
  387. const frameWindowId = (this.options.windowId || "0") + "." + frameIndex;
  388. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  389. DomProcessorHelper.setFrameEmptySrc(frameElement);
  390. frameElement.setAttribute("sandbox", "");
  391. if (frameData) {
  392. if (initialization) {
  393. const options = Object.create(this.options);
  394. options.insertSingleFileComment = false;
  395. options.insertFaviconLink = false;
  396. options.url = frameData.baseURI;
  397. options.windowId = frameWindowId;
  398. if (frameData.content) {
  399. options.content = frameData.content;
  400. frameData.processor = new PageProcessor(options);
  401. frameData.frameElement = frameElement;
  402. await frameData.processor.loadPage();
  403. return frameData.processor.initialize();
  404. }
  405. } else {
  406. if (frameData.processor) {
  407. await frameData.processor.preparePageData();
  408. const pageData = await frameData.processor.getPageData();
  409. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  410. }
  411. }
  412. }
  413. }));
  414. }
  415. async htmlImports(initialization) {
  416. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  417. if (!this.relImportProcessors) {
  418. this.relImportProcessors = new Map();
  419. }
  420. await Promise.all(linkElements.map(async linkElement => {
  421. if (initialization) {
  422. const resourceURL = linkElement.href;
  423. const options = Object.create(this.options);
  424. options.insertSingleFileComment = false;
  425. options.insertFaviconLink = false;
  426. options.url = resourceURL;
  427. if (resourceURL) {
  428. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  429. const processor = new PageProcessor(options);
  430. this.relImportProcessors.set(linkElement, processor);
  431. await processor.loadPage();
  432. return processor.initialize();
  433. }
  434. }
  435. } else {
  436. const processor = this.relImportProcessors.get(linkElement);
  437. if (processor) {
  438. this.relImportProcessors.delete(linkElement);
  439. const pageData = await processor.getPageData();
  440. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  441. } else {
  442. linkElement.setAttribute("href", EMPTY_DATA_URI);
  443. }
  444. }
  445. }));
  446. }
  447. async attributeStyles(initialization) {
  448. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  449. 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);
  450. element.setAttribute("style", stylesheetContent);
  451. }));
  452. }
  453. async linkStylesheets() {
  454. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  455. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  456. const styleElement = this.doc.createElement("style");
  457. styleElement.textContent = stylesheetContent;
  458. linkElement.parentElement.replaceChild(styleElement, linkElement);
  459. }));
  460. }
  461. }
  462. // ---------
  463. // DomHelper
  464. // ---------
  465. class DomProcessorHelper {
  466. static setFrameEmptySrc(frameElement) {
  467. if (frameElement.tagName == "OBJECT") {
  468. frameElement.setAttribute("data", "data:text/html,");
  469. } else {
  470. frameElement.setAttribute("srcdoc", "");
  471. frameElement.removeAttribute("src");
  472. }
  473. }
  474. static setFrameContent(frameElement, content) {
  475. if (frameElement.tagName == "OBJECT") {
  476. frameElement.setAttribute("data", "data:text/html," + content);
  477. } else {
  478. frameElement.setAttribute("srcdoc", content);
  479. frameElement.removeAttribute("src");
  480. }
  481. }
  482. static isolateElements(rootElement) {
  483. rootElement.querySelectorAll("*").forEach(element => {
  484. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) === "") {
  485. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  486. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  487. element.remove();
  488. }
  489. });
  490. isolateParentElements(rootElement.parentElement, rootElement);
  491. function isolateParentElements(parentElement, element) {
  492. if (parentElement) {
  493. Array.from(parentElement.childNodes).forEach(node => {
  494. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  495. node.remove();
  496. }
  497. });
  498. }
  499. element = element.parentElement;
  500. if (element && element.parentElement) {
  501. isolateParentElements(element.parentElement, element);
  502. }
  503. }
  504. }
  505. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  506. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  507. const imports = DomUtil.getImportFunctions(stylesheetContent);
  508. await Promise.all(imports.map(async cssImport => {
  509. const match = DomUtil.matchImport(cssImport);
  510. if (match) {
  511. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  512. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  513. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  514. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  515. if (stylesheetContent.indexOf(cssImport) != -1) {
  516. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  517. }
  518. }
  519. }
  520. }));
  521. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  522. if (imports.length) {
  523. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI, options);
  524. } else {
  525. return stylesheetContent;
  526. }
  527. }
  528. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  529. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  530. urlFunctions.map(urlFunction => {
  531. let resourceURL = DomUtil.matchURL(urlFunction);
  532. resourceURL = DomUtil.normalizeURL(resourceURL);
  533. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  534. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  535. }
  536. });
  537. return stylesheetContent;
  538. }
  539. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  540. resourceURL = DomUtil.normalizeURL(resourceURL);
  541. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  542. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  543. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  544. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  545. return stylesheetContent;
  546. }
  547. }
  548. static async processStylesheet(stylesheetContent, baseURI) {
  549. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  550. await Promise.all(urlFunctions.map(async urlFunction => {
  551. let resourceURL = DomUtil.matchURL(urlFunction);
  552. resourceURL = DomUtil.normalizeURL(resourceURL);
  553. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  554. const dataURI = await batchRequest.addURL(resourceURL);
  555. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  556. }
  557. }));
  558. return stylesheetContent;
  559. }
  560. static async processAttribute(resourceElements, attributeName, baseURI) {
  561. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  562. let resourceURL = resourceElement.getAttribute(attributeName);
  563. if (resourceURL) {
  564. resourceURL = DomUtil.normalizeURL(resourceURL);
  565. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  566. try {
  567. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  568. resourceElement.setAttribute(attributeName, dataURI);
  569. } catch (error) {
  570. // ignored
  571. }
  572. }
  573. }
  574. }));
  575. }
  576. static async processSrcset(resourceElements, attributeName, baseURI, parseSrcset) {
  577. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  578. const srcset = parseSrcset(resourceElement.getAttribute(attributeName));
  579. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  580. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  581. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  582. try {
  583. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  584. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  585. } catch (error) {
  586. // ignored
  587. }
  588. }
  589. }));
  590. resourceElement.setAttribute(attributeName, srcsetValues.join(","));
  591. }));
  592. }
  593. }
  594. // -------
  595. // DomUtil
  596. // -------
  597. const DATA_URI_PREFIX = "data:";
  598. const BLOB_URI_PREFIX = "blob:";
  599. const ABOUT_BLANK_URI = "about:blank";
  600. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  601. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  602. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  603. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  604. 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;
  605. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  606. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  607. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  608. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'([^']*)'\s*([^;]*)/i;
  609. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"([^"]*)"\s*([^;]*)/i;
  610. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*([^;]*)\s*([^;]*)/i;
  611. class DomUtil {
  612. static normalizeURL(url) {
  613. return url.split("#")[0];
  614. }
  615. static getUrlFunctions(stylesheetContent) {
  616. return stylesheetContent.match(REGEXP_URL_FN) || [];
  617. }
  618. static getImportFunctions(stylesheetContent) {
  619. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  620. }
  621. static matchURL(stylesheetContent) {
  622. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  623. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  624. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  625. return match && match[1];
  626. }
  627. static testValidPath(resourceURL) {
  628. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  629. }
  630. static matchImport(stylesheetContent) {
  631. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  632. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  633. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  634. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  635. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  636. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  637. if (match) {
  638. const [, resourceURL, media] = match;
  639. return { resourceURL, media };
  640. }
  641. }
  642. static removeCssComments(stylesheetContent) {
  643. let start, end;
  644. do {
  645. start = stylesheetContent.indexOf("/*");
  646. end = stylesheetContent.indexOf("*/", start);
  647. if (start != -1 && end != -1) {
  648. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  649. }
  650. } while (start != -1 && end != -1);
  651. return stylesheetContent;
  652. }
  653. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  654. if (mediaQuery) {
  655. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  656. } else {
  657. return stylesheetContent;
  658. }
  659. }
  660. }
  661. return { getClass };
  662. })();