content.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global browser, SingleFileBrowser, singlefile, frameTree, document, window, lazyLoader, setTimeout, docHelper */
  24. this.singlefile.top = this.singlefile.top || (() => {
  25. const MAX_CONTENT_SIZE = 64 * (1024 * 1024);
  26. const DOWNLOADER_FRAME_ID = "single-file-downloader";
  27. const SingleFile = SingleFileBrowser.getClass();
  28. let processing = false;
  29. browser.runtime.onMessage.addListener(message => {
  30. if (message.method == "content.save") {
  31. savePage(message);
  32. }
  33. });
  34. return true;
  35. async function savePage(message) {
  36. const options = message.options;
  37. if (!processing) {
  38. let selectionFound;
  39. if (options.selected) {
  40. selectionFound = await singlefile.ui.markSelection();
  41. }
  42. if (!options.selected || selectionFound) {
  43. processing = true;
  44. try {
  45. const page = await processPage(options);
  46. await downloadPage(page, options);
  47. } catch (error) {
  48. console.error(error); // eslint-disable-line no-console
  49. browser.runtime.sendMessage({ method: "ui.processError", error, options: {} });
  50. }
  51. } else {
  52. browser.runtime.sendMessage({ method: "ui.processCancelled", options: {} });
  53. }
  54. processing = false;
  55. }
  56. }
  57. async function processPage(options) {
  58. docHelper.initDoc(document);
  59. const iframe = document.getElementById(DOWNLOADER_FRAME_ID);
  60. if (iframe) {
  61. iframe.remove();
  62. }
  63. singlefile.ui.onStartPage(options);
  64. const processor = new SingleFile(options);
  65. const preInitializationPromises = [];
  66. options.insertSingleFileComment = true;
  67. if (!options.saveRawPage) {
  68. if (!options.removeFrames && this.frameTree) {
  69. let frameTreePromise;
  70. if (options.loadDeferredImages) {
  71. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frameTree.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frameTree.TIMEOUT_INIT_REQUEST_MESSAGE));
  72. } else {
  73. frameTreePromise = frameTree.getAsync(options);
  74. }
  75. singlefile.ui.onLoadingFrames();
  76. frameTreePromise.then(() => singlefile.ui.onLoadFrames());
  77. preInitializationPromises.push(frameTreePromise);
  78. }
  79. if (options.loadDeferredImages) {
  80. const lazyLoadPromise = lazyLoader.process(options);
  81. singlefile.ui.onLoadingDeferResources();
  82. lazyLoadPromise.then(() => singlefile.ui.onLoadDeferResources());
  83. preInitializationPromises.push(lazyLoadPromise);
  84. }
  85. }
  86. let index = 0, maxIndex = 0;
  87. options.onprogress = event => {
  88. if (event.type == event.RESOURCES_INITIALIZED) {
  89. maxIndex = event.detail.max;
  90. }
  91. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  92. if (event.type == event.RESOURCE_LOADED) {
  93. index++;
  94. }
  95. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex, options: {} });
  96. singlefile.ui.onLoadResource(index, maxIndex, options);
  97. } if (event.type == event.PAGE_ENDED) {
  98. browser.runtime.sendMessage({ method: "ui.processEnd", options: {} });
  99. } else if (!event.detail.frame) {
  100. if (event.type == event.PAGE_LOADING) {
  101. singlefile.ui.onPageLoading();
  102. } else if (event.type == event.PAGE_LOADED) {
  103. singlefile.ui.onLoadPage();
  104. } else if (event.type == event.STAGE_STARTED) {
  105. if (event.detail.step < 3) {
  106. singlefile.ui.onStartStage(event.detail.step);
  107. }
  108. } else if (event.type == event.STAGE_ENDED) {
  109. if (event.detail.step < 3) {
  110. singlefile.ui.onEndStage(event.detail.step);
  111. }
  112. } else if (event.type == event.STAGE_TASK_STARTED) {
  113. singlefile.ui.onStartStageTask(event.detail.step, event.detail.task);
  114. } else if (event.type == event.STAGE_TASK_ENDED) {
  115. singlefile.ui.onEndStageTask(event.detail.step, event.detail.task);
  116. }
  117. }
  118. };
  119. [options.framesData] = await Promise.all(preInitializationPromises);
  120. const selectedFrame = options.framesData && options.framesData.find(frameData => frameData.requestedFrame);
  121. options.win = window;
  122. if (selectedFrame) {
  123. options.content = selectedFrame.content;
  124. options.url = selectedFrame.baseURI;
  125. options.canvasData = selectedFrame.canvasData;
  126. options.fontsData = selectedFrame.fontsData;
  127. options.stylesheetsData = selectedFrame.stylesheetsData;
  128. options.imagesData = selectedFrame.imagesData;
  129. options.postersData = selectedFrame.postersData;
  130. options.usedFonts = selectedFrame.usedFonts;
  131. options.shadowRootsData = selectedFrame.shadowRootsData;
  132. } else {
  133. options.doc = document;
  134. }
  135. await processor.run();
  136. if (!options.saveRawPage && !options.removeFrames && this.frameTree) {
  137. this.frameTree.cleanup(options);
  138. }
  139. if (options.confirmInfobarContent) {
  140. options.infobarContent = singlefile.ui.prompt("Infobar content", options.infobarContent) || "";
  141. }
  142. const page = await processor.getPageData();
  143. if (options.selected) {
  144. singlefile.ui.unmarkSelection();
  145. }
  146. singlefile.ui.onEndPage(options);
  147. if (options.displayStats) {
  148. console.log("SingleFile stats"); // eslint-disable-line no-console
  149. console.table(page.stats); // eslint-disable-line no-console
  150. }
  151. return page;
  152. }
  153. async function downloadPage(page, options) {
  154. if (options.backgroundSave) {
  155. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < page.content.length; blockIndex++) {
  156. const message = { method: "downloads.download", confirmFilename: options.confirmFilename, filenameConflictAction: options.filenameConflictAction, filename: page.filename, saveToClipboard: options.saveToClipboard };
  157. message.truncated = page.content.length > MAX_CONTENT_SIZE;
  158. if (message.truncated) {
  159. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > page.content.length;
  160. message.content = page.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  161. } else {
  162. message.content = page.content;
  163. }
  164. await browser.runtime.sendMessage(message);
  165. }
  166. } else {
  167. if (options.saveToClipboard) {
  168. saveToClipboard(page);
  169. } else {
  170. downloadPageForeground(page, options);
  171. }
  172. }
  173. }
  174. function downloadPageForeground(page, options) {
  175. if (options.confirmFilename) {
  176. page.filename = singlefile.ui.prompt("File name", page.filename);
  177. }
  178. if (page.filename && page.filename.length) {
  179. const iframe = document.createElement("iframe");
  180. iframe.id = DOWNLOADER_FRAME_ID;
  181. iframe.style.setProperty("display", "inline-block", "important");
  182. iframe.style.setProperty("max-width", "0", "important");
  183. iframe.style.setProperty("max-height", "0", "important");
  184. iframe.style.setProperty("border-width", "0", "important");
  185. iframe.style.setProperty("margin", "0", "important");
  186. iframe.src = browser.runtime.getURL("/extension/core/pages/downloader.html");
  187. iframe.onload = () => iframe.contentWindow.postMessage(JSON.stringify([page.filename, page.content]), "*");
  188. document.body.appendChild(iframe);
  189. }
  190. }
  191. function saveToClipboard(page) {
  192. const command = "copy";
  193. document.addEventListener(command, listener);
  194. document.execCommand(command);
  195. document.removeEventListener(command, listener);
  196. function listener(event) {
  197. event.clipboardData.setData("text/html", page.content);
  198. event.clipboardData.setData("text/plain", page.content);
  199. event.preventDefault();
  200. }
  201. }
  202. })();