single-file-core.js 28 KB

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