content.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. const MESSAGE_PREFIX = "__SingleFile__::";
  23. const SingleFileClass = SingleFile.getClass();
  24. let processing = false;
  25. browser.runtime.onMessage.addListener(message => {
  26. if (message.savePage) {
  27. savePage(message);
  28. }
  29. });
  30. addEventListener("message", event => {
  31. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  32. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  33. if (message.savePage) {
  34. savePage(message);
  35. }
  36. }
  37. });
  38. return true;
  39. async function savePage(message) {
  40. const options = message.options;
  41. if (!processing && !options.frameId) {
  42. let selectionFound;
  43. if (options.selected) {
  44. selectionFound = await markSelection();
  45. }
  46. if (!options.selected || selectionFound) {
  47. processing = true;
  48. try {
  49. const page = await processPage(options);
  50. await downloadPage(page, options);
  51. } catch (error) {
  52. console.error(error); // eslint-disable-line no-console
  53. browser.runtime.sendMessage({ processError: true, error, options: { autoSave: false } });
  54. }
  55. } else {
  56. browser.runtime.sendMessage({ processCancelled: true, options: { autoSave: false } });
  57. }
  58. processing = false;
  59. }
  60. }
  61. async function markSelection() {
  62. let selectionFound = markSelectedContent();
  63. if (selectionFound) {
  64. return selectionFound;
  65. } else {
  66. const selectedArea = await singlefile.ui.getSelectedArea();
  67. if (selectedArea) {
  68. markSelectedArea(selectedArea);
  69. selectionFound = true;
  70. }
  71. return selectionFound;
  72. }
  73. }
  74. async function processPage(options) {
  75. singlefile.ui.init();
  76. const processor = new SingleFileClass(options);
  77. options.insertSingleFileComment = true;
  78. options.insertFaviconLink = true;
  79. if (!options.removeFrames && this.frameTree) {
  80. options.framesData = await frameTree.getAsync(options);
  81. }
  82. options.doc = document;
  83. options.win = window;
  84. let index = 0, maxIndex = 0;
  85. options.onprogress = event => {
  86. if (event.type == event.RESOURCES_INITIALIZED) {
  87. maxIndex = event.details.max;
  88. }
  89. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  90. if (event.type == event.RESOURCE_LOADED) {
  91. index++;
  92. }
  93. browser.runtime.sendMessage({ processProgress: true, index, maxIndex, options: { autoSave: false } });
  94. if (options.shadowEnabled) {
  95. singlefile.ui.onprogress(index, maxIndex);
  96. }
  97. } else if (event.type == event.PAGE_ENDED) {
  98. browser.runtime.sendMessage({ processEnd: true, options: { autoSave: false } });
  99. }
  100. };
  101. if (options.lazyLoadImages) {
  102. await lazyLoadResources();
  103. }
  104. await processor.initialize();
  105. await processor.preparePageData();
  106. const page = await processor.getPageData();
  107. if (options.selected) {
  108. unmarkSelectedContent();
  109. }
  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. async function lazyLoadResources() {
  121. const scriptURL = browser.runtime.getURL("lib/single-file/lazy-loader-before.js");
  122. const scriptBeforeElement = document.createElement("script");
  123. scriptBeforeElement.src = scriptURL;
  124. document.body.appendChild(scriptBeforeElement);
  125. const promise = new Promise(resolve => {
  126. scriptBeforeElement.onerror = resolve;
  127. scriptBeforeElement.onload = () => setTimeout(() => {
  128. scriptBeforeElement.remove();
  129. const scriptURL = browser.runtime.getURL("lib/single-file/lazy-loader-after.js");
  130. const scriptAfterElement = document.createElement("script");
  131. scriptAfterElement.src = scriptURL;
  132. document.body.appendChild(scriptAfterElement);
  133. scriptAfterElement.onload = () => scriptAfterElement.remove();
  134. resolve();
  135. }, 250);
  136. });
  137. return promise;
  138. }
  139. function markSelectedContent() {
  140. const selection = getSelection();
  141. const range = selection.rangeCount ? selection.getRangeAt(0) : null;
  142. let selectionFound = false;
  143. if (range && range.commonAncestorContainer) {
  144. const treeWalker = document.createTreeWalker(range.commonAncestorContainer);
  145. const ancestorElement = range.commonAncestorContainer != Node.ELEMENT_NODE ? range.commonAncestorContainer.parentElement : range.commonAncestorContainer;
  146. while (treeWalker.nextNode() && treeWalker.currentNode != range.endContainer) {
  147. if (treeWalker.currentNode == range.startContainer) {
  148. selectionFound = true;
  149. }
  150. if (selectionFound) {
  151. const element = treeWalker.currentNode.nodeType == Node.ELEMENT_NODE ? treeWalker.currentNode : treeWalker.currentNode.parentElement;
  152. element.setAttribute(SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME, "");
  153. }
  154. }
  155. if (selectionFound) {
  156. ancestorElement.setAttribute(SingleFileClass.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME, "");
  157. }
  158. }
  159. return selectionFound;
  160. }
  161. function markSelectedArea(selectedAreaElement) {
  162. selectedAreaElement.setAttribute(SingleFileClass.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME, "");
  163. selectedAreaElement.querySelectorAll("*").forEach(element => element.setAttribute(SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME, ""));
  164. }
  165. function unmarkSelectedContent() {
  166. document.querySelectorAll("[" + SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME));
  167. document.querySelectorAll("[" + SingleFileClass.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SingleFileClass.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME));
  168. }
  169. async function downloadPage(page, options) {
  170. if (options.backgroundSave) {
  171. const response = await browser.runtime.sendMessage({ download: true, url: page.url, confirmFilename: options.confirmFilename, filename: page.filename });
  172. if (response.notSupported) {
  173. const response = await browser.runtime.sendMessage({ download: true, content: page.content, confirmFilename: options.confirmFilename, filename: page.filename });
  174. if (response.notSupported) {
  175. downloadPageFallback(page, options);
  176. }
  177. } else {
  178. URL.revokeObjectURL(page.url);
  179. }
  180. } else {
  181. downloadPageFallback(page, options);
  182. }
  183. }
  184. function downloadPageFallback(page, options) {
  185. if (options.confirmFilename) {
  186. page.filename = prompt("File name", page.filename);
  187. }
  188. if (page.filename && page.filename.length) {
  189. const link = document.createElement("a");
  190. document.body.appendChild(link);
  191. link.download = page.filename;
  192. link.href = page.url;
  193. link.dispatchEvent(new MouseEvent("click"));
  194. link.remove();
  195. URL.revokeObjectURL(page.url);
  196. }
  197. }
  198. })();