core.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. /* global browser, SingleFile, singlefile, Blob */
  21. singlefile.core = (() => {
  22. const FORBIDDEN_URLS = ["https://chrome.google.com", "https://addons.mozilla.org"];
  23. const contentScriptFiles = [
  24. "/lib/browser-polyfill/custom-browser-polyfill.js",
  25. "/lib/single-file/doc-helper.js",
  26. "/lib/single-file/base64.js",
  27. "/lib/single-file/parse-srcset.js",
  28. "/lib/fetch/content/fetch.js",
  29. "/lib/single-file/single-file-core.js",
  30. "/lib/single-file/single-file-browser.js",
  31. "/extension/index.js",
  32. "/extension/ui/content/content-ui.js",
  33. "/extension/core/content/content.js"
  34. ];
  35. const optionalContentScriptFiles = {
  36. compressHTML: [
  37. "/lib/single-file/htmlmini.js",
  38. "/lib/single-file/serializer.js"
  39. ],
  40. compressCSS: [
  41. "/lib/single-file/uglifycss.js"
  42. ],
  43. removeAlternativeFonts: [
  44. "/lib/single-file/fonts-minifier.js"
  45. ],
  46. removeUnusedStyles: [
  47. "/lib/single-file/css-what.js",
  48. "/lib/single-file/parse-css.js",
  49. "/lib/single-file/css-minifier.js"
  50. ],
  51. lazyLoadImages: [
  52. "/lib/single-file/lazy-loader.js",
  53. ]
  54. };
  55. browser.runtime.onMessage.addListener((request, sender) => {
  56. if (request.getConfig) {
  57. return singlefile.config.get();
  58. }
  59. if (request.download) {
  60. try {
  61. if (request.content) {
  62. request.url = URL.createObjectURL(new Blob([request.content], { type: "text/html" }));
  63. }
  64. return downloadPage(request, { confirmFilename: request.confirmFilename, incognito: sender.tab.incognito })
  65. .catch(error => {
  66. if (error.message && error.message.includes("'incognito'")) {
  67. return downloadPage(request, { confirmFilename: request.confirmFilename });
  68. } else {
  69. return { notSupported: true };
  70. }
  71. });
  72. } catch (error) {
  73. return Promise.resolve({ notSupported: true });
  74. }
  75. }
  76. if (request.processContent) {
  77. processBackgroundTab(sender.tab, request);
  78. }
  79. });
  80. browser.tabs.onRemoved.addListener(async tabId => {
  81. const tabsData = await singlefile.storage.get();
  82. delete tabsData[tabId];
  83. await singlefile.storage.set(tabsData);
  84. });
  85. return {
  86. async processTab(tab, processOptions = {}) {
  87. const options = await singlefile.config.get();
  88. Object.keys(processOptions).forEach(key => options[key] = processOptions[key]);
  89. return new Promise(async (resolve, reject) => {
  90. const processPromise = processStart(tab, options);
  91. try {
  92. await processPromise;
  93. } catch (error) {
  94. reject(error);
  95. }
  96. resolve();
  97. });
  98. },
  99. isAllowedURL(url) {
  100. return url && (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("file://")) && !FORBIDDEN_URLS.find(storeUrl => url.startsWith(storeUrl));
  101. }
  102. };
  103. async function processBackgroundTab(tab, message) {
  104. const options = await singlefile.config.get();
  105. options.content = message.content;
  106. options.url = message.url;
  107. options.framesData = message.framesData;
  108. options.canvasData = message.canvasData;
  109. options.emptyStyleRulesText = message.emptyStyleRulesText;
  110. options.insertSingleFileComment = true;
  111. options.insertFaviconLink = true;
  112. options.backgroundTab = true;
  113. options.autoSave = true;
  114. options.incognito = tab.incognito;
  115. options.onprogress = async event => {
  116. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  117. singlefile.ui.button.onProgress(tab.id, event.details.index, event.details.max, { autoSave: true });
  118. } else if (event.type == event.PAGE_ENDED) {
  119. singlefile.ui.button.onEnd(tab.id, { autoSave: true });
  120. }
  121. };
  122. const processor = new (SingleFile.getClass())(options);
  123. await processor.initialize();
  124. await processor.preparePageData();
  125. const page = processor.getPageData();
  126. const date = new Date();
  127. page.filename = page.title + (options.appendSaveDate ? " (" + date.toISOString().split("T")[0] + " " + date.toLocaleTimeString() + ")" : "") + ".html";
  128. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  129. return downloadPage(page, options);
  130. }
  131. async function downloadPage(page, options) {
  132. const downloadInfo = {
  133. url: page.url,
  134. saveAs: options.confirmFilename,
  135. filename: page.filename.replace(/[/\\?%*:|"<>\x7F]+/g, "_")
  136. };
  137. if (options.incognito) {
  138. downloadInfo.incognito = true;
  139. }
  140. const downloadId = await browser.downloads.download(downloadInfo);
  141. return new Promise(resolve => {
  142. URL.revokeObjectURL(page.url);
  143. browser.downloads.onChanged.addListener(onChanged);
  144. function onChanged(event) {
  145. if (event.id == downloadId && event.state && event.state.current == "complete") {
  146. resolve({});
  147. browser.downloads.onChanged.removeListener(onChanged);
  148. }
  149. }
  150. });
  151. }
  152. async function processStart(tab, options) {
  153. await executeScripts(tab.id, getContentScriptFiles(options), { allFrames: false });
  154. if (options.frameId) {
  155. await browser.tabs.sendMessage(tab.id, { processStartFrame: true, options }, { frameId: options.frameId });
  156. } else {
  157. await browser.tabs.sendMessage(tab.id, { processStart: true, options });
  158. }
  159. }
  160. async function executeScripts(tabId, scriptFiles, details) {
  161. for (let file of scriptFiles) {
  162. details.file = file;
  163. await browser.tabs.executeScript(tabId, details);
  164. }
  165. }
  166. function getContentScriptFiles(options) {
  167. let files = contentScriptFiles;
  168. Object.keys(optionalContentScriptFiles).forEach(option => {
  169. if (options[option]) {
  170. files = optionalContentScriptFiles[option].concat(files);
  171. }
  172. });
  173. return files;
  174. }
  175. })();