content.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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, SingleFile, singlefile, FrameTree, document, Blob, MouseEvent, getSelection, prompt, addEventListener, Node, window */
  21. this.singlefile.top = this.singlefile.top || (() => {
  22. let processing = false;
  23. let autoSaveTimeout;
  24. browser.runtime.onMessage.addListener(async message => {
  25. if (message.processStart) {
  26. savePage(message);
  27. }
  28. });
  29. addEventListener("message", event => {
  30. if (typeof event.data == "string" && event.data.startsWith("__SingleFile__::")) {
  31. const message = JSON.parse(event.data.substring("__SingleFile__".length + 2));
  32. savePage(message);
  33. }
  34. });
  35. return true;
  36. async function savePage(message) {
  37. const options = message.options;
  38. if ((!processing || options.autoSave) && !options.frameId) {
  39. if (!autoSaveTimeout && options.autoSave && options.autoSaveDelay) {
  40. autoSaveTimeout = setTimeout(() => savePage(message), options.autoSaveDelay * 1000);
  41. } else {
  42. autoSaveTimeout = null;
  43. if (!options.autoSave) {
  44. processing = true;
  45. }
  46. try {
  47. const page = await processPage(options);
  48. await downloadPage(page, options);
  49. revokeDownloadURL(page);
  50. } catch (error) {
  51. console.error(error); // eslint-disable-line no-console
  52. browser.runtime.sendMessage({ processError: true, error, options: { autoSave: options.autoSave } });
  53. }
  54. if (!options.autoSave) {
  55. processing = false;
  56. }
  57. }
  58. }
  59. }
  60. async function processPage(options) {
  61. options.insertSingleFileComment = true;
  62. options.insertFaviconLink = true;
  63. if (options.shadowEnabled && !options.autoSave) {
  64. singlefile.ui.init();
  65. }
  66. options = await getOptions(options);
  67. const processor = new (SingleFile.getClass())(options);
  68. if (options.selected) {
  69. markSelectedContent(processor.SELECTED_CONTENT_ATTRIBUTE_NAME, processor.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  70. }
  71. await processor.initialize();
  72. await processor.preparePageData();
  73. const page = processor.getPageData();
  74. if (options.selected) {
  75. unmarkSelectedContent(processor.SELECTED_CONTENT_ATTRIBUTE_NAME, processor.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  76. }
  77. const date = new Date();
  78. page.filename = page.title + (options.appendSaveDate ? " (" + date.toISOString().split("T")[0] + " " + date.toLocaleTimeString() + ")" : "") + ".html";
  79. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  80. if (options.shadowEnabled && !options.autoSave) {
  81. singlefile.ui.end();
  82. }
  83. if (options.displayStats) {
  84. console.log("SingleFile stats"); // eslint-disable-line no-console
  85. console.table(page.stats); // eslint-disable-line no-console
  86. }
  87. return page;
  88. }
  89. function revokeDownloadURL(page) {
  90. URL.revokeObjectURL(page.url);
  91. }
  92. function markSelectedContent(SELECTED_CONTENT_ATTRIBUTE_NAME, SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME) {
  93. const selection = getSelection();
  94. const range = selection.rangeCount ? selection.getRangeAt(0) : null;
  95. const treeWalker = document.createTreeWalker(range.commonAncestorContainer);
  96. let selectionFound = false;
  97. const ancestorElement = range.commonAncestorContainer != Node.ELEMENT_NODE ? range.commonAncestorContainer.parentElement : range.commonAncestorContainer;
  98. ancestorElement.setAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME, "");
  99. while (treeWalker.nextNode() && treeWalker.currentNode != range.endContainer) {
  100. if (treeWalker.currentNode == range.startContainer) {
  101. selectionFound = true;
  102. }
  103. if (selectionFound) {
  104. const element = treeWalker.currentNode.nodeType == Node.ELEMENT_NODE ? treeWalker.currentNode : treeWalker.currentNode.parentElement;
  105. element.setAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME, "");
  106. }
  107. }
  108. }
  109. function unmarkSelectedContent(SELECTED_CONTENT_ATTRIBUTE_NAME, SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME) {
  110. document.querySelectorAll("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME));
  111. document.querySelectorAll("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME));
  112. }
  113. async function getOptions(options) {
  114. options.doc = document;
  115. options.win = window;
  116. if (!options.removeFrames) {
  117. options.framesData = await FrameTree.getFramesData(options);
  118. }
  119. options.jsEnabled = true;
  120. options.onprogress = async event => {
  121. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  122. try {
  123. await browser.runtime.sendMessage({ processProgress: true, index: event.details.index, maxIndex: event.details.max, options: { autoSave: options.autoSave } });
  124. } catch (error) {
  125. /* ignored */
  126. }
  127. if (options.shadowEnabled && !options.autoSave) {
  128. singlefile.ui.onprogress(event);
  129. }
  130. } else if (event.type == event.PAGE_ENDED) {
  131. try {
  132. await browser.runtime.sendMessage({ processEnd: true, options: { autoSave: options.autoSave } });
  133. } catch (error) {
  134. /* ignored */
  135. }
  136. }
  137. };
  138. return options;
  139. }
  140. async function downloadPage(page, options) {
  141. if (options.backgroundSave) {
  142. const response = await browser.runtime.sendMessage({ download: true, url: page.url, confirmFilename: options.confirmFilename, filename: page.filename });
  143. if (response.notSupported) {
  144. const response = await browser.runtime.sendMessage({ download: true, content: page.content, confirmFilename: options.confirmFilename, filename: page.filename });
  145. if (response.notSupported) {
  146. downloadPageFallback(page, options);
  147. }
  148. }
  149. } else {
  150. downloadPageFallback(page, options);
  151. }
  152. }
  153. function downloadPageFallback(page, options) {
  154. if (options.confirmFilename) {
  155. page.filename = prompt("File name", page.filename);
  156. }
  157. if (page.filename && page.filename.length) {
  158. const link = document.createElement("a");
  159. document.body.appendChild(link);
  160. link.download = page.filename;
  161. link.href = page.url;
  162. link.dispatchEvent(new MouseEvent("click"));
  163. link.remove();
  164. }
  165. }
  166. })();