content.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. let processing = false;
  24. browser.runtime.onMessage.addListener(message => {
  25. if (message.savePage) {
  26. savePage(message);
  27. }
  28. });
  29. addEventListener("message", event => {
  30. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  31. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  32. if (message.savePage) {
  33. savePage(message);
  34. }
  35. }
  36. });
  37. return true;
  38. async function savePage(message) {
  39. const options = message.options;
  40. if (!processing && !options.frameId) {
  41. processing = true;
  42. try {
  43. const page = await processPage(options);
  44. await downloadPage(page, options);
  45. } catch (error) {
  46. console.error(error); // eslint-disable-line no-console
  47. browser.runtime.sendMessage({ processError: true, error, options: { autoSave: false } });
  48. }
  49. processing = false;
  50. }
  51. }
  52. async function processPage(options) {
  53. singlefile.ui.init();
  54. const processor = new (SingleFile.getClass())(options);
  55. options.insertSingleFileComment = true;
  56. options.insertFaviconLink = true;
  57. if (!options.removeFrames && this.frameTree) {
  58. options.framesData = await frameTree.getAsync(options);
  59. }
  60. options.doc = document;
  61. options.win = window;
  62. let index = 0, maxIndex = 0;
  63. options.onprogress = event => {
  64. if (event.type == event.RESOURCES_INITIALIZED) {
  65. maxIndex = event.details.max;
  66. }
  67. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  68. if (event.type == event.RESOURCE_LOADED) {
  69. index++;
  70. }
  71. browser.runtime.sendMessage({ processProgress: true, index, maxIndex, options: { autoSave: false } });
  72. if (options.shadowEnabled) {
  73. singlefile.ui.onprogress(index, maxIndex);
  74. }
  75. } else if (event.type == event.PAGE_ENDED) {
  76. browser.runtime.sendMessage({ processEnd: true, options: { autoSave: false } });
  77. }
  78. };
  79. if (options.selected) {
  80. const selectionFound = markSelectedContent(processor.SELECTED_CONTENT_ATTRIBUTE_NAME, processor.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  81. if (!selectionFound) {
  82. options.selected = false;
  83. }
  84. }
  85. if (options.lazyLoadImages) {
  86. await lazyLoadResources();
  87. }
  88. await processor.initialize();
  89. await processor.preparePageData();
  90. const page = await processor.getPageData();
  91. if (options.selected) {
  92. unmarkSelectedContent(processor.SELECTED_CONTENT_ATTRIBUTE_NAME, processor.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  93. }
  94. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  95. if (options.shadowEnabled) {
  96. singlefile.ui.end();
  97. }
  98. if (options.displayStats) {
  99. console.log("SingleFile stats"); // eslint-disable-line no-console
  100. console.table(page.stats); // eslint-disable-line no-console
  101. }
  102. return page;
  103. }
  104. async function lazyLoadResources() {
  105. const scriptURL = browser.runtime.getURL("lib/single-file/lazy-loader-before.js");
  106. const scriptBeforeElement = document.createElement("script");
  107. scriptBeforeElement.src = scriptURL;
  108. document.body.appendChild(scriptBeforeElement);
  109. const promise = new Promise(resolve => {
  110. scriptBeforeElement.onerror = resolve;
  111. scriptBeforeElement.onload = () => setTimeout(() => {
  112. scriptBeforeElement.remove();
  113. const scriptURL = browser.runtime.getURL("lib/single-file/lazy-loader-after.js");
  114. const scriptAfterElement = document.createElement("script");
  115. scriptAfterElement.src = scriptURL;
  116. document.body.appendChild(scriptAfterElement);
  117. scriptAfterElement.onload = () => scriptAfterElement.remove();
  118. resolve();
  119. }, 100);
  120. });
  121. return promise;
  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. } else {
  154. URL.revokeObjectURL(page.url);
  155. }
  156. } else {
  157. downloadPageFallback(page, options);
  158. }
  159. }
  160. function downloadPageFallback(page, options) {
  161. if (options.confirmFilename) {
  162. page.filename = prompt("File name", page.filename);
  163. }
  164. if (page.filename && page.filename.length) {
  165. const link = document.createElement("a");
  166. document.body.appendChild(link);
  167. link.download = page.filename;
  168. link.href = page.url;
  169. link.dispatchEvent(new MouseEvent("click"));
  170. link.remove();
  171. URL.revokeObjectURL(page.url);
  172. }
  173. }
  174. })();