single-file-core.js 29 KB

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