core.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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/rules-matcher.js",
  50. "/lib/single-file/css-minifier.js"
  51. ],
  52. lazyLoadImages: [
  53. "/lib/single-file/lazy-loader.js",
  54. ]
  55. };
  56. browser.runtime.onMessage.addListener((request, sender) => {
  57. if (request.getConfig) {
  58. return singlefile.config.get();
  59. }
  60. if (request.download) {
  61. try {
  62. if (request.content) {
  63. request.url = URL.createObjectURL(new Blob([request.content], { type: "text/html" }));
  64. }
  65. return downloadPage(request, { confirmFilename: request.confirmFilename, incognito: sender.tab.incognito })
  66. .catch(error => {
  67. if (error.message && error.message.includes("'incognito'")) {
  68. return downloadPage(request, { confirmFilename: request.confirmFilename });
  69. } else {
  70. return { notSupported: true };
  71. }
  72. });
  73. } catch (error) {
  74. return Promise.resolve({ notSupported: true });
  75. }
  76. }
  77. if (request.processContent) {
  78. processBackgroundTab(sender.tab, request);
  79. }
  80. });
  81. browser.tabs.onRemoved.addListener(async tabId => {
  82. const tabsData = await singlefile.storage.get();
  83. delete tabsData[tabId];
  84. await singlefile.storage.set(tabsData);
  85. });
  86. return { saveTab, autoSaveTab, isAllowedURL };
  87. async function saveTab(tab, processOptions) {
  88. const options = await singlefile.config.get();
  89. Object.keys(processOptions).forEach(key => options[key] = processOptions[key]);
  90. return new Promise(async (resolve, reject) => {
  91. const processPromise = saveStart(tab, options);
  92. try {
  93. await processPromise;
  94. } catch (error) {
  95. reject(error);
  96. }
  97. resolve();
  98. });
  99. }
  100. async function autoSaveTab(tab) {
  101. const options = await singlefile.config.get();
  102. return new Promise(async (resolve, reject) => {
  103. const processPromise = autoSaveStart(tab, options);
  104. try {
  105. await processPromise;
  106. } catch (error) {
  107. reject(error);
  108. }
  109. resolve();
  110. });
  111. }
  112. function isAllowedURL(url) {
  113. return url && (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("file://")) && !FORBIDDEN_URLS.find(storeUrl => url.startsWith(storeUrl));
  114. }
  115. async function processBackgroundTab(tab, message) {
  116. const options = await singlefile.config.get();
  117. options.content = message.content;
  118. options.url = message.url;
  119. options.framesData = message.framesData;
  120. options.canvasData = message.canvasData;
  121. options.emptyStyleRulesText = message.emptyStyleRulesText;
  122. options.insertSingleFileComment = true;
  123. options.insertFaviconLink = true;
  124. options.backgroundTab = true;
  125. options.autoSave = true;
  126. options.incognito = tab.incognito;
  127. options.onprogress = async event => {
  128. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  129. singlefile.ui.button.onProgress(tab.id, event.details.index, event.details.max, { autoSave: true });
  130. } else if (event.type == event.PAGE_ENDED) {
  131. singlefile.ui.button.onEnd(tab.id, { autoSave: true });
  132. }
  133. };
  134. const processor = new (SingleFile.getClass())(options);
  135. await processor.initialize();
  136. await processor.preparePageData();
  137. const page = processor.getPageData();
  138. const date = new Date();
  139. page.filename = page.title + (options.appendSaveDate ? " (" + date.toISOString().split("T")[0] + " " + date.toLocaleTimeString() + ")" : "") + ".html";
  140. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  141. return downloadPage(page, options);
  142. }
  143. async function downloadPage(page, options) {
  144. const downloadInfo = {
  145. url: page.url,
  146. saveAs: options.confirmFilename,
  147. filename: page.filename.replace(/[/\\?%*:|"<>\x7F]+/g, "_")
  148. };
  149. if (options.incognito) {
  150. downloadInfo.incognito = true;
  151. }
  152. const downloadId = await browser.downloads.download(downloadInfo);
  153. return new Promise(resolve => {
  154. browser.downloads.onChanged.addListener(onChanged);
  155. function onChanged(event) {
  156. if (event.id == downloadId && event.state && event.state.current == "complete") {
  157. URL.revokeObjectURL(page.url);
  158. resolve({});
  159. browser.downloads.onChanged.removeListener(onChanged);
  160. }
  161. }
  162. });
  163. }
  164. async function saveStart(tab, options) {
  165. await executeScripts(tab.id, getContentScriptFiles(options), false);
  166. if (options.frameId) {
  167. await browser.tabs.sendMessage(tab.id, { saveFrame: true, options }, { frameId: options.frameId });
  168. } else {
  169. await browser.tabs.sendMessage(tab.id, { savePage: true, options });
  170. }
  171. }
  172. async function autoSaveStart(tab, options) {
  173. await executeScripts(tab.id, getContentScriptFiles(options), false);
  174. await browser.tabs.sendMessage(tab.id, { autoSavePage: true, options });
  175. }
  176. async function executeScripts(tabId, scriptFiles, allFrames) {
  177. return Promise.all(scriptFiles.map(file => browser.tabs.executeScript(tabId, { file, allFrames })));
  178. }
  179. function getContentScriptFiles(options) {
  180. let files = contentScriptFiles;
  181. Object.keys(optionalContentScriptFiles).forEach(option => {
  182. if (options[option]) {
  183. files = optionalContentScriptFiles[option].concat(files);
  184. }
  185. });
  186. return files;
  187. }
  188. })();