single-file-core.js 29 KB

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