content.js 6.7 KB

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