content.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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, getComputedStyle, prompt, addEventListener */
  21. this.singlefile.top = this.singlefile.top || (() => {
  22. const PROGRESS_LOADED_COEFFICIENT = 2;
  23. let processing = false;
  24. browser.runtime.onMessage.addListener(async message => {
  25. savePage(message);
  26. return {};
  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. savePage(message);
  32. }
  33. });
  34. return true;
  35. async function savePage(message) {
  36. if (message.processStart && !processing && !message.options.frameId) {
  37. processing = true;
  38. try {
  39. const page = await processMessage(message);
  40. downloadPage(page, message.options);
  41. revokeDownloadURL(page);
  42. } catch (error) {
  43. console.error(error); // eslint-disable-line no-console
  44. browser.runtime.sendMessage({ processError: true, error });
  45. }
  46. processing = false;
  47. }
  48. }
  49. async function processMessage(message) {
  50. const options = await getOptions(message.options);
  51. const processor = new (SingleFile.getClass())(options);
  52. fixInlineScripts();
  53. fixHeadNoScripts();
  54. if (options.selected) {
  55. selectSelectedContent(processor.SELECTED_CONTENT_ATTRIBUTE_NAME);
  56. }
  57. if (!options.removeFrames) {
  58. hideHeadFrames();
  59. }
  60. if (options.removeHiddenElements) {
  61. selectRemovedElements(processor.REMOVED_CONTENT_ATTRIBUTE_NAME);
  62. }
  63. options.url = options.url || document.location.href;
  64. options.content = options.content || getDoctype(document) + document.documentElement.outerHTML;
  65. await processor.initialize();
  66. if (options.removeHiddenElements) {
  67. unselectRemovedElements(processor.REMOVED_CONTENT_ATTRIBUTE_NAME);
  68. }
  69. if (options.shadowEnabled) {
  70. singlefile.ui.init();
  71. }
  72. await processor.preparePageData();
  73. const page = processor.getPageData();
  74. if (options.selected) {
  75. unselectSelectedContent(processor.SELECTED_CONTENT_ATTRIBUTE_NAME);
  76. }
  77. const date = new Date();
  78. page.filename = page.title + (options.appendSaveDate ? " (" + date.toISOString().split("T")[0] + " " + date.toLocaleTimeString() + ")" : "") + ".html";
  79. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  80. if (options.shadowEnabled) {
  81. singlefile.ui.end();
  82. }
  83. return page;
  84. }
  85. function revokeDownloadURL(page) {
  86. URL.revokeObjectURL(page.url);
  87. }
  88. function fixInlineScripts() {
  89. document.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  90. }
  91. function hideHeadFrames() {
  92. document.head.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.hidden = true);
  93. }
  94. function fixHeadNoScripts() {
  95. document.head.querySelectorAll("noscript").forEach(noscriptElement => document.body.insertBefore(noscriptElement, document.body.firstChild));
  96. }
  97. function selectRemovedElements(REMOVED_CONTENT_ATTRIBUTE_NAME) {
  98. document.querySelectorAll("html > body *:not(style):not(script):not(link)").forEach(element => {
  99. const style = getComputedStyle(element);
  100. if (element.hidden || style.display == "none" || ((style.opacity === 0 || style.visibility == "hidden") && !element.clientWidth && !element.clientHeight)) {
  101. element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
  102. }
  103. });
  104. }
  105. function unselectRemovedElements(REMOVED_CONTENT_ATTRIBUTE_NAME) {
  106. document.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  107. }
  108. function selectSelectedContent(SELECTED_CONTENT_ATTRIBUTE_NAME) {
  109. const selection = getSelection();
  110. const range = selection.rangeCount ? selection.getRangeAt(0) : null;
  111. let node;
  112. if (range && range.startOffset != range.endOffset) {
  113. node = range.commonAncestorContainer;
  114. if (node.nodeType != node.ELEMENT_NODE) {
  115. node = node.parentElement;
  116. }
  117. }
  118. node.setAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME, "");
  119. }
  120. function unselectSelectedContent(SELECTED_CONTENT_ATTRIBUTE_NAME) {
  121. document.querySelectorAll("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME));
  122. }
  123. async function getOptions(options) {
  124. options.canvasData = getCanvasData();
  125. if (!options.removeFrames) {
  126. options.framesData = await FrameTree.getFramesData();
  127. }
  128. options.jsEnabled = true;
  129. let indexLoaded = 0, indexLoading = 0;
  130. options.onprogress = event => {
  131. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED || event.type == event.RESOURCE_LOADING) {
  132. if (event.type == event.RESOURCE_LOADED) {
  133. indexLoaded = event.details.index;
  134. }
  135. if (event.type == event.RESOURCE_LOADING) {
  136. indexLoading = event.details.index;
  137. }
  138. browser.runtime.sendMessage({ processProgress: true, index: (indexLoaded * PROGRESS_LOADED_COEFFICIENT) + indexLoading, maxIndex: event.details.max * (PROGRESS_LOADED_COEFFICIENT + 1) });
  139. } else if (event.type == event.PAGE_ENDED) {
  140. browser.runtime.sendMessage({ processEnd: true });
  141. }
  142. };
  143. return options;
  144. }
  145. function getCanvasData() {
  146. const canvasData = [];
  147. document.querySelectorAll("canvas").forEach(canvasElement => {
  148. try {
  149. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: canvasElement.clientWidth, height: canvasElement.clientHeight });
  150. } catch (error) {
  151. canvasData.push(null);
  152. }
  153. });
  154. return canvasData;
  155. }
  156. function getDoctype(doc) {
  157. const docType = doc.doctype;
  158. let docTypeString;
  159. if (docType) {
  160. docTypeString = "<!DOCTYPE " + docType.nodeName;
  161. if (docType.publicId) {
  162. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  163. if (docType.systemId)
  164. docTypeString += " \"" + docType.systemId + "\"";
  165. } else if (docType.systemId)
  166. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  167. if (docType.internalSubset)
  168. docTypeString += " [" + docType.internalSubset + "]";
  169. return docTypeString + ">\n";
  170. }
  171. return "";
  172. }
  173. function downloadPage(page, options) {
  174. if (options.confirmFilename) {
  175. page.filename = prompt("File name", page.filename);
  176. }
  177. if (page.filename && page.filename.length) {
  178. const link = document.createElement("a");
  179. document.body.appendChild(link);
  180. link.download = page.filename;
  181. link.href = page.url;
  182. link.dispatchEvent(new MouseEvent("click"));
  183. link.remove();
  184. }
  185. }
  186. })();