content.js 7.8 KB

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