content.js 6.5 KB

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