content.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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, Blob, MouseEvent, addEventListener, window, lazyLoader, URL, timeout */
  21. this.singlefile.top = this.singlefile.top || (() => {
  22. const MESSAGE_PREFIX = "__SingleFile__::";
  23. const MAX_CONTENT_SIZE = 64 * (1024 * 1024);
  24. const SingleFile = SingleFileBrowser.getClass();
  25. let processing = false;
  26. browser.runtime.onMessage.addListener(message => {
  27. if (message.savePage) {
  28. savePage(message);
  29. }
  30. });
  31. addEventListener("message", event => {
  32. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  33. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  34. if (message.savePage) {
  35. savePage(message);
  36. }
  37. }
  38. });
  39. return true;
  40. async function savePage(message) {
  41. const options = message.options;
  42. if (!processing && !options.frameId) {
  43. let selectionFound;
  44. if (options.selected) {
  45. selectionFound = await singlefile.ui.markSelection();
  46. }
  47. if (!options.selected || selectionFound) {
  48. processing = true;
  49. try {
  50. const page = await processPage(options);
  51. await downloadPage(page, options);
  52. } catch (error) {
  53. console.error(error); // eslint-disable-line no-console
  54. browser.runtime.sendMessage({ processError: true, error, options: {} });
  55. }
  56. } else {
  57. browser.runtime.sendMessage({ processCancelled: true, options: {} });
  58. }
  59. processing = false;
  60. }
  61. }
  62. async function processPage(options) {
  63. singlefile.ui.onStartPage();
  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 => timeout.set(() => 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 && options.shadowEnabled) {
  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({ processProgress: true, index, maxIndex, options: {} });
  96. if (options.shadowEnabled) {
  97. singlefile.ui.onLoadResource(index, maxIndex);
  98. }
  99. } if (event.type == event.PAGE_ENDED) {
  100. browser.runtime.sendMessage({ processEnd: true, options: {} });
  101. } else if (options.shadowEnabled && !event.detail.frame) {
  102. if (event.type == event.PAGE_LOADING) {
  103. singlefile.ui.onPageLoading();
  104. } else if (event.type == event.PAGE_LOADED) {
  105. singlefile.ui.onLoadPage();
  106. } else if (event.type == event.STAGE_STARTED) {
  107. if (event.detail.step < 3) {
  108. singlefile.ui.onStartStage(event.detail.step);
  109. }
  110. } else if (event.type == event.STAGE_ENDED) {
  111. if (event.detail.step < 3) {
  112. singlefile.ui.onEndStage(event.detail.step);
  113. }
  114. } else if (event.type == event.STAGE_TASK_STARTED) {
  115. singlefile.ui.onStartStageTask(event.detail.step, event.detail.task);
  116. } else if (event.type == event.STAGE_TASK_ENDED) {
  117. singlefile.ui.onEndStageTask(event.detail.step, event.detail.task);
  118. }
  119. }
  120. };
  121. [options.framesData] = await Promise.all(preInitializationPromises);
  122. options.doc = document;
  123. options.win = window;
  124. await processor.run();
  125. if (!options.saveRawPage && !options.removeFrames && this.frameTree) {
  126. this.frameTree.cleanup(options);
  127. }
  128. if (options.confirmInfobarContent) {
  129. options.infobarContent = singlefile.ui.prompt("Infobar content", options.infobarContent) || "";
  130. }
  131. const page = await processor.getPageData();
  132. if (options.selected) {
  133. singlefile.ui.unmarkSelection();
  134. }
  135. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  136. if (options.shadowEnabled) {
  137. singlefile.ui.onEndPage();
  138. }
  139. if (options.displayStats) {
  140. console.log("SingleFile stats"); // eslint-disable-line no-console
  141. console.table(page.stats); // eslint-disable-line no-console
  142. }
  143. return page;
  144. }
  145. async function downloadPage(page, options) {
  146. if (options.backgroundSave) {
  147. const response = await browser.runtime.sendMessage({ download: true, url: page.url, confirmFilename: options.confirmFilename, filenameConflictAction: options.filenameConflictAction, filename: page.filename });
  148. if (response.notSupported) {
  149. let response;
  150. for (let blockIndex = 0; (!response || !response.notSupported) && (blockIndex * MAX_CONTENT_SIZE < page.content.length); blockIndex++) {
  151. const message = { download: true, confirmFilename: options.confirmFilename, filenameConflictAction: options.filenameConflictAction, filename: page.filename };
  152. message.truncated = page.content.length > MAX_CONTENT_SIZE;
  153. if (message.truncated) {
  154. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > page.content.length;
  155. message.content = page.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  156. } else {
  157. message.content = page.content;
  158. }
  159. response = await browser.runtime.sendMessage(message);
  160. }
  161. if (response.notSupported) {
  162. downloadPageFallback(page, options);
  163. }
  164. } else {
  165. URL.revokeObjectURL(page.url);
  166. }
  167. } else {
  168. downloadPageFallback(page, options);
  169. }
  170. }
  171. function downloadPageFallback(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 = page.url;
  180. link.dispatchEvent(new MouseEvent("click"));
  181. link.remove();
  182. URL.revokeObjectURL(page.url);
  183. }
  184. }
  185. })();