content.js 6.8 KB

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