content.js 7.1 KB

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