content.js 7.0 KB

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