content.js 7.3 KB

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