content.js 8.1 KB

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