content.js 6.6 KB

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