single-file-core.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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 WIN_ID_ATTRIBUTE_NAME = "data-frame-tree-win-id";
  193. const batchRequest = new BatchRequest();
  194. class DOMProcessor {
  195. constructor(options) {
  196. this.options = options;
  197. this.baseURI = options.url;
  198. }
  199. async loadPage(pageContent) {
  200. if (!pageContent || this.options.saveRawPage) {
  201. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  202. }
  203. this.dom = DOM.create(pageContent, this.baseURI);
  204. this.DOMParser = this.dom.DOMParser;
  205. this.doc = this.dom.document;
  206. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  207. await DOMProcessor.loadEscapedFragmentPage();
  208. }
  209. }
  210. async loadEscapedFragmentPage() {
  211. if (this.baseURI.includes("?")) {
  212. this.baseURI += "&";
  213. } else {
  214. this.baseURI += "?";
  215. }
  216. this.baseURI += ESCAPED_FRAGMENT;
  217. await this.loadPage();
  218. }
  219. async retrieveResources(onloadListener) {
  220. await batchRequest.run(onloadListener, this.options);
  221. }
  222. getPageData() {
  223. if (this.options.selected) {
  224. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  225. if (rootElement) {
  226. DomProcessorHelper.isolateElements(rootElement);
  227. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  228. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  229. }
  230. }
  231. const titleElement = this.doc.querySelector("title");
  232. let title;
  233. if (titleElement) {
  234. title = titleElement.textContent.trim();
  235. }
  236. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  237. return {
  238. title: title || (this.baseURI && matchTitle ? matchTitle[1] : ""),
  239. content: this.dom.serialize()
  240. };
  241. }
  242. insertNoscriptContents() {
  243. if (this.DOMParser) {
  244. this.doc.querySelectorAll("noscript").forEach(element => {
  245. const fragment = this.doc.createDocumentFragment();
  246. Array.from(element.childNodes).forEach(node => {
  247. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  248. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  249. this.doc.importNode(node);
  250. fragment.appendChild(node);
  251. });
  252. });
  253. element.parentElement.replaceChild(fragment, element);
  254. });
  255. }
  256. }
  257. lazyLoadImages() {
  258. this.dom.lazyLoader.process(this.doc);
  259. }
  260. removeDiscardedResources() {
  261. 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());
  262. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  263. this.doc.querySelectorAll("[onerror]").forEach(element => element.removeAttribute("onerror"));
  264. if (this.options.removeAudioSrc) {
  265. this.doc.querySelectorAll("audio[src], audio > source[src]").forEach(element => element.removeAttribute("src"));
  266. }
  267. if (this.options.removeVideoSrc) {
  268. this.doc.querySelectorAll("video[src], video > source[src]").forEach(element => element.removeAttribute("src"));
  269. }
  270. }
  271. removeBase() {
  272. this.doc.querySelectorAll("base").forEach(element => element.remove());
  273. }
  274. removeScripts() {
  275. this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])").forEach(element => element.remove());
  276. }
  277. removeFrames() {
  278. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  279. }
  280. removeImports() {
  281. this.doc.querySelectorAll("link[rel=import]").forEach(element => element.remove());
  282. }
  283. resetCharsetMeta() {
  284. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  285. const metaElement = this.doc.createElement("meta");
  286. metaElement.setAttribute("charset", "utf-8");
  287. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  288. }
  289. insertFaviconLink() {
  290. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  291. if (!faviconElement) {
  292. faviconElement = this.doc.createElement("link");
  293. faviconElement.setAttribute("type", "image/x-icon");
  294. faviconElement.setAttribute("rel", "shortcut icon");
  295. faviconElement.setAttribute("href", "/favicon.ico");
  296. this.doc.head.appendChild(faviconElement);
  297. }
  298. }
  299. resolveHrefs() {
  300. this.doc.querySelectorAll("[href]").forEach(element => {
  301. const match = element.href && element.href.match(/(.*)#.*$/);
  302. if (!match || match[1] != this.baseURI) {
  303. element.setAttribute("href", element.href);
  304. }
  305. });
  306. }
  307. removeUnusedCSSRules() {
  308. this.dom.rulesMinifier(this.doc);
  309. }
  310. removeHiddenElements() {
  311. this.doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.remove());
  312. }
  313. compressHTML(postProcess) {
  314. if (postProcess) {
  315. this.dom.htmlmini.postProcess(this.doc);
  316. } else {
  317. this.dom.htmlmini.process(this.doc, { preservedSpaceAttributeName: PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME });
  318. this.doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  319. }
  320. }
  321. insertSingleFileCommentNode() {
  322. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  323. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  324. }
  325. replaceCanvasElements() {
  326. if (this.options.canvasData) {
  327. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  328. const canvasData = this.options.canvasData[indexCanvasElement];
  329. if (canvasData) {
  330. const imgElement = this.doc.createElement("img");
  331. imgElement.setAttribute("src", canvasData.dataURI);
  332. Array.from(canvasElement.attributes).forEach(attribute => {
  333. if (attribute.value) {
  334. imgElement.setAttribute(attribute.name, attribute.value);
  335. }
  336. });
  337. if (!imgElement.width && canvasData.width) {
  338. imgElement.style.pixelWidth = canvasData.width;
  339. }
  340. if (!imgElement.height && canvasData.height) {
  341. imgElement.style.pixelHeight = canvasData.height;
  342. }
  343. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  344. }
  345. });
  346. }
  347. }
  348. async pageResources() {
  349. const resourcePromises = [
  350. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  351. 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),
  352. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  353. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  354. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  355. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI, this.dom.parseSrcset)
  356. ];
  357. if (!this.options.removeAudioSrc) {
  358. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  359. }
  360. if (!this.options.removeVideoSrc) {
  361. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  362. }
  363. if (this.options.lazyLoadImages) {
  364. const imageSelectors = this.dom.lazyLoader.imageSelectors;
  365. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  366. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI, this.dom.parseSrcset)));
  367. }
  368. await resourcePromises;
  369. }
  370. async inlineStylesheets(initialization) {
  371. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  372. 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);
  373. styleElement.textContent = !initialization && this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  374. }));
  375. }
  376. async scripts() {
  377. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  378. if (scriptElement.src) {
  379. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  380. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  381. }
  382. scriptElement.removeAttribute("src");
  383. }));
  384. }
  385. async frames(initialization) {
  386. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  387. await Promise.all(frameElements.map(async (frameElement) => {
  388. const frameWindowId = frameElement.getAttribute(WIN_ID_ATTRIBUTE_NAME);
  389. if (frameWindowId) {
  390. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  391. DomProcessorHelper.setFrameEmptySrc(frameElement);
  392. frameElement.setAttribute("sandbox", "");
  393. if (frameData) {
  394. if (initialization) {
  395. const options = Object.create(this.options);
  396. options.insertSingleFileComment = false;
  397. options.insertFaviconLink = false;
  398. options.url = frameData.baseURI;
  399. options.windowId = frameWindowId;
  400. if (frameData.content) {
  401. options.content = frameData.content;
  402. frameData.processor = new PageProcessor(options);
  403. frameData.frameElement = frameElement;
  404. await frameData.processor.loadPage();
  405. return frameData.processor.initialize();
  406. }
  407. } else {
  408. if (frameData.processor) {
  409. await frameData.processor.preparePageData();
  410. const pageData = await frameData.processor.getPageData();
  411. frameElement.removeAttribute(WIN_ID_ATTRIBUTE_NAME);
  412. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  413. }
  414. }
  415. }
  416. }
  417. }));
  418. }
  419. async htmlImports(initialization) {
  420. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  421. if (!this.relImportProcessors) {
  422. this.relImportProcessors = new Map();
  423. }
  424. await Promise.all(linkElements.map(async linkElement => {
  425. if (initialization) {
  426. const resourceURL = linkElement.href;
  427. const options = Object.create(this.options);
  428. options.insertSingleFileComment = false;
  429. options.insertFaviconLink = false;
  430. options.url = resourceURL;
  431. if (resourceURL) {
  432. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  433. const processor = new PageProcessor(options);
  434. this.relImportProcessors.set(linkElement, processor);
  435. await processor.loadPage();
  436. return processor.initialize();
  437. }
  438. }
  439. } else {
  440. const processor = this.relImportProcessors.get(linkElement);
  441. if (processor) {
  442. this.relImportProcessors.delete(linkElement);
  443. const pageData = await processor.getPageData();
  444. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  445. } else {
  446. linkElement.setAttribute("href", EMPTY_DATA_URI);
  447. }
  448. }
  449. }));
  450. }
  451. async attributeStyles(initialization) {
  452. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  453. 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);
  454. element.setAttribute("style", stylesheetContent);
  455. }));
  456. }
  457. async linkStylesheets() {
  458. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  459. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  460. const styleElement = this.doc.createElement("style");
  461. styleElement.textContent = stylesheetContent;
  462. linkElement.parentElement.replaceChild(styleElement, linkElement);
  463. }));
  464. }
  465. }
  466. // ---------
  467. // DomHelper
  468. // ---------
  469. class DomProcessorHelper {
  470. static setFrameEmptySrc(frameElement) {
  471. if (frameElement.tagName == "OBJECT") {
  472. frameElement.setAttribute("data", "data:text/html,");
  473. } else {
  474. frameElement.setAttribute("srcdoc", "");
  475. frameElement.removeAttribute("src");
  476. }
  477. }
  478. static setFrameContent(frameElement, content) {
  479. if (frameElement.tagName == "OBJECT") {
  480. frameElement.setAttribute("data", "data:text/html," + content);
  481. } else {
  482. frameElement.setAttribute("srcdoc", content);
  483. frameElement.removeAttribute("src");
  484. }
  485. }
  486. static isolateElements(rootElement) {
  487. rootElement.querySelectorAll("*").forEach(element => {
  488. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) === "") {
  489. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  490. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  491. element.remove();
  492. }
  493. });
  494. isolateParentElements(rootElement.parentElement, rootElement);
  495. function isolateParentElements(parentElement, element) {
  496. if (parentElement) {
  497. Array.from(parentElement.childNodes).forEach(node => {
  498. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  499. node.remove();
  500. }
  501. });
  502. }
  503. element = element.parentElement;
  504. if (element && element.parentElement) {
  505. isolateParentElements(element.parentElement, element);
  506. }
  507. }
  508. }
  509. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  510. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  511. const imports = DomUtil.getImportFunctions(stylesheetContent);
  512. await Promise.all(imports.map(async cssImport => {
  513. const match = DomUtil.matchImport(cssImport);
  514. if (match) {
  515. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  516. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  517. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  518. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  519. if (stylesheetContent.indexOf(cssImport) != -1) {
  520. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  521. }
  522. }
  523. }
  524. }));
  525. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  526. if (imports.length) {
  527. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI, options);
  528. } else {
  529. return stylesheetContent;
  530. }
  531. }
  532. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  533. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  534. urlFunctions.map(urlFunction => {
  535. let resourceURL = DomUtil.matchURL(urlFunction);
  536. resourceURL = DomUtil.normalizeURL(resourceURL);
  537. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  538. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  539. }
  540. });
  541. return stylesheetContent;
  542. }
  543. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  544. resourceURL = DomUtil.normalizeURL(resourceURL);
  545. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  546. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  547. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  548. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  549. return stylesheetContent;
  550. }
  551. }
  552. static async processStylesheet(stylesheetContent, baseURI) {
  553. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  554. await Promise.all(urlFunctions.map(async urlFunction => {
  555. let resourceURL = DomUtil.matchURL(urlFunction);
  556. resourceURL = DomUtil.normalizeURL(resourceURL);
  557. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  558. const dataURI = await batchRequest.addURL(resourceURL);
  559. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  560. }
  561. }));
  562. return stylesheetContent;
  563. }
  564. static async processAttribute(resourceElements, attributeName, baseURI) {
  565. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  566. let resourceURL = resourceElement.getAttribute(attributeName);
  567. if (resourceURL) {
  568. resourceURL = DomUtil.normalizeURL(resourceURL);
  569. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  570. try {
  571. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  572. resourceElement.setAttribute(attributeName, dataURI);
  573. } catch (error) {
  574. // ignored
  575. }
  576. }
  577. }
  578. }));
  579. }
  580. static async processSrcset(resourceElements, attributeName, baseURI, parseSrcset) {
  581. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  582. const srcset = parseSrcset(resourceElement.getAttribute(attributeName));
  583. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  584. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  585. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  586. try {
  587. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  588. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  589. } catch (error) {
  590. // ignored
  591. }
  592. }
  593. }));
  594. resourceElement.setAttribute(attributeName, srcsetValues.join(","));
  595. }));
  596. }
  597. }
  598. // -------
  599. // DomUtil
  600. // -------
  601. const DATA_URI_PREFIX = "data:";
  602. const BLOB_URI_PREFIX = "blob:";
  603. const ABOUT_BLANK_URI = "about:blank";
  604. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  605. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  606. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  607. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  608. 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;
  609. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  610. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  611. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  612. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'([^']*)'\s*([^;]*)/i;
  613. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"([^"]*)"\s*([^;]*)/i;
  614. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*([^;]*)\s*([^;]*)/i;
  615. class DomUtil {
  616. static normalizeURL(url) {
  617. return url.split("#")[0];
  618. }
  619. static getUrlFunctions(stylesheetContent) {
  620. return stylesheetContent.match(REGEXP_URL_FN) || [];
  621. }
  622. static getImportFunctions(stylesheetContent) {
  623. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  624. }
  625. static matchURL(stylesheetContent) {
  626. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  627. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  628. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  629. return match && match[1];
  630. }
  631. static testValidPath(resourceURL) {
  632. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  633. }
  634. static matchImport(stylesheetContent) {
  635. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  636. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  637. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  638. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  639. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  640. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  641. if (match) {
  642. const [, resourceURL, media] = match;
  643. return { resourceURL, media };
  644. }
  645. }
  646. static removeCssComments(stylesheetContent) {
  647. let start, end;
  648. do {
  649. start = stylesheetContent.indexOf("/*");
  650. end = stylesheetContent.indexOf("*/", start);
  651. if (start != -1 && end != -1) {
  652. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  653. }
  654. } while (start != -1 && end != -1);
  655. return stylesheetContent;
  656. }
  657. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  658. if (mediaQuery) {
  659. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  660. } else {
  661. return stylesheetContent;
  662. }
  663. }
  664. }
  665. return { getClass };
  666. })();