1
0

content.js 6.2 KB

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