content.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. * Copyright 2018 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 SingleFile = SingleFileBrowser.getClass();
  24. let processing = false;
  25. browser.runtime.onMessage.addListener(message => {
  26. if (message.savePage) {
  27. savePage(message);
  28. }
  29. });
  30. addEventListener("message", event => {
  31. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  32. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  33. if (message.savePage) {
  34. savePage(message);
  35. }
  36. }
  37. });
  38. return true;
  39. async function savePage(message) {
  40. const options = message.options;
  41. if (!processing && !options.frameId) {
  42. let selectionFound;
  43. if (options.selected) {
  44. selectionFound = await singlefile.ui.markSelection();
  45. }
  46. if (!options.selected || selectionFound) {
  47. processing = true;
  48. try {
  49. const page = await processPage(options);
  50. await downloadPage(page, options);
  51. } catch (error) {
  52. console.error(error); // eslint-disable-line no-console
  53. browser.runtime.sendMessage({ processError: true, error, options: { autoSave: false } });
  54. }
  55. } else {
  56. browser.runtime.sendMessage({ processCancelled: true, options: { autoSave: false } });
  57. }
  58. processing = false;
  59. }
  60. }
  61. async function processPage(options) {
  62. singlefile.ui.onStartPage();
  63. const processor = new SingleFile(options);
  64. const preInitializationPromises = [];
  65. options.insertSingleFileComment = true;
  66. options.insertFaviconLink = true;
  67. if (!options.removeFrames && this.frameTree) {
  68. let frameTreePromise;
  69. if (options.lazyLoadImages) {
  70. frameTreePromise = new Promise(resolve => timeout.set(() => resolve(frameTree.getAsync(options)), options.maxLazyLoadImagesIdleTime - frameTree.TIMEOUT_INIT_REQUEST_MESSAGE));
  71. } else {
  72. frameTreePromise = frameTree.getAsync(options);
  73. }
  74. singlefile.ui.onLoadingFrames();
  75. frameTreePromise.then(() => singlefile.ui.onLoadFrames());
  76. preInitializationPromises.push(frameTreePromise);
  77. }
  78. if (options.lazyLoadImages && options.shadowEnabled) {
  79. const lazyLoadPromise = lazyLoader.process(options);
  80. singlefile.ui.onLoadingDeferResources();
  81. lazyLoadPromise.then(() => singlefile.ui.onLoadDeferResources());
  82. preInitializationPromises.push(lazyLoadPromise);
  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({ processProgress: true, index, maxIndex, options: { autoSave: false } });
  94. if (options.shadowEnabled) {
  95. singlefile.ui.onLoadResource(index, maxIndex);
  96. }
  97. } if (event.type == event.PAGE_ENDED) {
  98. browser.runtime.sendMessage({ processEnd: true, options: { autoSave: false } });
  99. } else if (options.shadowEnabled && !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. options.doc = document;
  121. options.win = window;
  122. await processor.initialize();
  123. await processor.run();
  124. if (options.confirmInfobar) {
  125. options.infobarContent = singlefile.ui.prompt("Infobar content", options.infobarContent) || "";
  126. }
  127. const page = await processor.getPageData();
  128. if (options.selected) {
  129. singlefile.ui.unmarkSelection();
  130. }
  131. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  132. if (options.shadowEnabled) {
  133. singlefile.ui.onEndPage();
  134. }
  135. if (options.displayStats) {
  136. console.log("SingleFile stats"); // eslint-disable-line no-console
  137. console.table(page.stats); // eslint-disable-line no-console
  138. }
  139. return page;
  140. }
  141. async function downloadPage(page, options) {
  142. if (options.backgroundSave) {
  143. const response = await browser.runtime.sendMessage({ download: true, url: page.url, confirmFilename: options.confirmFilename, conflictAction: options.conflictAction, filename: page.filename });
  144. if (response.notSupported) {
  145. const response = await browser.runtime.sendMessage({ download: true, content: page.content, confirmFilename: options.confirmFilename, conflictAction: options.conflictAction, filename: page.filename });
  146. if (response.notSupported) {
  147. downloadPageFallback(page, options);
  148. }
  149. } else {
  150. URL.revokeObjectURL(page.url);
  151. }
  152. } else {
  153. downloadPageFallback(page, options);
  154. }
  155. }
  156. function downloadPageFallback(page, options) {
  157. if (options.confirmFilename) {
  158. page.filename = singlefile.ui.prompt("File name", page.filename);
  159. }
  160. if (page.filename && page.filename.length) {
  161. const link = document.createElement("a");
  162. document.body.appendChild(link);
  163. link.download = page.filename;
  164. link.href = page.url;
  165. link.dispatchEvent(new MouseEvent("click"));
  166. link.remove();
  167. URL.revokeObjectURL(page.url);
  168. }
  169. }
  170. })();