content.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. /*
  2. * Copyright 2010-2019 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, SingleFileBrowser, singlefile, frameTree, document, MouseEvent, window, lazyLoader, URL, setTimeout, docHelper, Blob */
  21. this.singlefile.top = this.singlefile.top || (() => {
  22. const MAX_CONTENT_SIZE = 64 * (1024 * 1024);
  23. const SingleFile = SingleFileBrowser.getClass();
  24. let processing = false;
  25. browser.runtime.onMessage.addListener(message => {
  26. if (message.method == "content.save") {
  27. savePage(message);
  28. }
  29. });
  30. return true;
  31. async function savePage(message) {
  32. const options = message.options;
  33. if (!processing) {
  34. let selectionFound;
  35. if (options.selected) {
  36. selectionFound = await singlefile.ui.markSelection();
  37. }
  38. if (!options.selected || selectionFound) {
  39. processing = true;
  40. try {
  41. const page = await processPage(options);
  42. await downloadPage(page, options);
  43. } catch (error) {
  44. console.error(error); // eslint-disable-line no-console
  45. browser.runtime.sendMessage({ method: "ui.processError", error, options: {} });
  46. }
  47. } else {
  48. browser.runtime.sendMessage({ method: "ui.processCancelled", options: {} });
  49. }
  50. processing = false;
  51. }
  52. }
  53. async function processPage(options) {
  54. docHelper.initDoc(document);
  55. if (options.shadowEnabled) {
  56. singlefile.ui.onStartPage();
  57. }
  58. const processor = new SingleFile(options);
  59. const preInitializationPromises = [];
  60. options.insertSingleFileComment = true;
  61. if (!options.saveRawPage) {
  62. if (!options.removeFrames && this.frameTree) {
  63. let frameTreePromise;
  64. if (options.loadDeferredImages) {
  65. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frameTree.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frameTree.TIMEOUT_INIT_REQUEST_MESSAGE));
  66. } else {
  67. frameTreePromise = frameTree.getAsync(options);
  68. }
  69. if (options.shadowEnabled) {
  70. singlefile.ui.onLoadingFrames();
  71. frameTreePromise.then(() => singlefile.ui.onLoadFrames());
  72. }
  73. preInitializationPromises.push(frameTreePromise);
  74. }
  75. if (options.loadDeferredImages) {
  76. const lazyLoadPromise = lazyLoader.process(options);
  77. if (options.shadowEnabled) {
  78. singlefile.ui.onLoadingDeferResources();
  79. lazyLoadPromise.then(() => singlefile.ui.onLoadDeferResources());
  80. }
  81. preInitializationPromises.push(lazyLoadPromise);
  82. }
  83. }
  84. let index = 0, maxIndex = 0;
  85. options.onprogress = event => {
  86. if (event.type == event.RESOURCES_INITIALIZED) {
  87. maxIndex = event.detail.max;
  88. }
  89. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  90. if (event.type == event.RESOURCE_LOADED) {
  91. index++;
  92. }
  93. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex, options: {} });
  94. if (options.shadowEnabled) {
  95. singlefile.ui.onLoadResource(index, maxIndex);
  96. }
  97. } if (event.type == event.PAGE_ENDED) {
  98. browser.runtime.sendMessage({ method: "ui.processEnd", options: {} });
  99. } else if (options.shadowEnabled) {
  100. if (!event.detail.frame) {
  101. if (event.type == event.PAGE_LOADING) {
  102. singlefile.ui.onPageLoading();
  103. } else if (event.type == event.PAGE_LOADED) {
  104. singlefile.ui.onLoadPage();
  105. } else if (event.type == event.STAGE_STARTED) {
  106. if (event.detail.step < 3) {
  107. singlefile.ui.onStartStage(event.detail.step);
  108. }
  109. } else if (event.type == event.STAGE_ENDED) {
  110. if (event.detail.step < 3) {
  111. singlefile.ui.onEndStage(event.detail.step);
  112. }
  113. } else if (event.type == event.STAGE_TASK_STARTED) {
  114. singlefile.ui.onStartStageTask(event.detail.step, event.detail.task);
  115. } else if (event.type == event.STAGE_TASK_ENDED) {
  116. singlefile.ui.onEndStageTask(event.detail.step, event.detail.task);
  117. }
  118. }
  119. }
  120. };
  121. [options.framesData] = await Promise.all(preInitializationPromises);
  122. const selectedFrame = options.framesData && options.framesData.find(frameData => frameData.requestedFrame);
  123. options.win = window;
  124. if (selectedFrame) {
  125. options.content = selectedFrame.content;
  126. options.url = selectedFrame.baseURI;
  127. options.canvasData = selectedFrame.canvasData;
  128. options.fontsData = selectedFrame.fontsData;
  129. options.stylesheetContents = selectedFrame.stylesheetContents;
  130. options.imageData = selectedFrame.imageData;
  131. options.postersData = selectedFrame.postersData;
  132. options.usedFonts = selectedFrame.usedFonts;
  133. options.shadowRootContents = selectedFrame.shadowRootContents;
  134. } else {
  135. options.doc = document;
  136. }
  137. await processor.run();
  138. if (!options.saveRawPage && !options.removeFrames && this.frameTree) {
  139. this.frameTree.cleanup(options);
  140. }
  141. if (options.confirmInfobarContent) {
  142. options.infobarContent = singlefile.ui.prompt("Infobar content", options.infobarContent) || "";
  143. }
  144. const page = await processor.getPageData();
  145. if (options.selected) {
  146. singlefile.ui.unmarkSelection();
  147. }
  148. if (options.shadowEnabled) {
  149. singlefile.ui.onEndPage();
  150. }
  151. if (options.displayStats) {
  152. console.log("SingleFile stats"); // eslint-disable-line no-console
  153. console.table(page.stats); // eslint-disable-line no-console
  154. }
  155. return page;
  156. }
  157. async function downloadPage(page, options) {
  158. if (options.backgroundSave) {
  159. let response;
  160. for (let blockIndex = 0; !response && (blockIndex * MAX_CONTENT_SIZE < page.content.length); blockIndex++) {
  161. const message = { method: "downloads.download", confirmFilename: options.confirmFilename, filenameConflictAction: options.filenameConflictAction, filename: page.filename, saveToClipboard: options.saveToClipboard };
  162. message.truncated = page.content.length > MAX_CONTENT_SIZE;
  163. if (message.truncated) {
  164. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > page.content.length;
  165. message.content = page.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  166. } else {
  167. message.content = page.content;
  168. }
  169. response = await browser.runtime.sendMessage(message);
  170. }
  171. } else {
  172. if (options.saveToClipboard) {
  173. saveToClipboard(page);
  174. } else {
  175. downloadPageForeground(page, options);
  176. }
  177. }
  178. }
  179. function downloadPageForeground(page, options) {
  180. if (options.confirmFilename) {
  181. page.filename = singlefile.ui.prompt("File name", page.filename);
  182. }
  183. if (page.filename && page.filename.length) {
  184. const link = document.createElement("a");
  185. document.body.appendChild(link);
  186. link.download = page.filename;
  187. link.href = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  188. link.dispatchEvent(new MouseEvent("click"));
  189. link.remove();
  190. URL.revokeObjectURL(page.url);
  191. }
  192. }
  193. function saveToClipboard(page) {
  194. const command = "copy";
  195. document.addEventListener(command, listener);
  196. document.execCommand(command);
  197. document.removeEventListener(command, listener);
  198. function listener(event) {
  199. event.clipboardData.setData("text/html", page.content);
  200. event.clipboardData.setData("text/plain", page.content);
  201. event.preventDefault();
  202. }
  203. }
  204. })();