content.js 7.5 KB

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