content.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. } 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 fixInlineScripts() {
  78. document.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  79. }
  80. function hideHeadFrames() {
  81. document.head.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.hidden = true);
  82. }
  83. function fixHeadNoScripts() {
  84. document.head.querySelectorAll("noscript").forEach(noscriptElement => document.body.insertBefore(noscriptElement, document.body.firstChild));
  85. }
  86. function selectRemovedElements(REMOVED_CONTENT_ATTRIBUTE_NAME) {
  87. document.querySelectorAll("html > body *:not(style):not(script):not(link)").forEach(element => {
  88. const style = getComputedStyle(element);
  89. if (element.hidden || style.display == "none" || ((style.opacity === 0 || style.visibility == "hidden") && !element.clientWidth && !element.clientHeight)) {
  90. element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
  91. }
  92. });
  93. }
  94. function unselectRemovedElements(REMOVED_CONTENT_ATTRIBUTE_NAME) {
  95. document.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  96. }
  97. function selectSelectedContent(SELECTED_CONTENT_ATTRIBUTE_NAME) {
  98. const selection = getSelection();
  99. const range = selection.rangeCount ? selection.getRangeAt(0) : null;
  100. let node;
  101. if (range && range.startOffset != range.endOffset) {
  102. node = range.commonAncestorContainer;
  103. if (node.nodeType != node.ELEMENT_NODE) {
  104. node = node.parentElement;
  105. }
  106. }
  107. node.setAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME, "");
  108. }
  109. function unselectSelectedContent(SELECTED_CONTENT_ATTRIBUTE_NAME) {
  110. document.querySelectorAll("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME));
  111. }
  112. async function getOptions(options) {
  113. options.canvasData = getCanvasData();
  114. if (!options.removeFrames) {
  115. options.framesData = await FrameTree.getFramesData();
  116. }
  117. options.jsEnabled = true;
  118. let indexLoaded = 0, indexLoading = 0;
  119. options.onprogress = event => {
  120. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED || event.type == event.RESOURCE_LOADING) {
  121. if (event.type == event.RESOURCE_LOADED) {
  122. indexLoaded = event.details.index;
  123. }
  124. if (event.type == event.RESOURCE_LOADING) {
  125. indexLoading = event.details.index;
  126. }
  127. browser.runtime.sendMessage({ processProgress: true, index: (indexLoaded * PROGRESS_LOADED_COEFFICIENT) + indexLoading, maxIndex: event.details.max * (PROGRESS_LOADED_COEFFICIENT + 1) });
  128. } else if (event.type == event.PAGE_ENDED) {
  129. browser.runtime.sendMessage({ processEnd: true });
  130. }
  131. };
  132. return options;
  133. }
  134. function getCanvasData() {
  135. const canvasData = [];
  136. document.querySelectorAll("canvas").forEach(canvasElement => {
  137. try {
  138. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: canvasElement.clientWidth, height: canvasElement.clientHeight });
  139. } catch (e) {
  140. canvasData.push(null);
  141. }
  142. });
  143. return canvasData;
  144. }
  145. function getDoctype(doc) {
  146. const docType = doc.doctype;
  147. let docTypeString;
  148. if (docType) {
  149. docTypeString = "<!DOCTYPE " + docType.nodeName;
  150. if (docType.publicId) {
  151. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  152. if (docType.systemId)
  153. docTypeString += " \"" + docType.systemId + "\"";
  154. } else if (docType.systemId)
  155. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  156. if (docType.internalSubset)
  157. docTypeString += " [" + docType.internalSubset + "]";
  158. return docTypeString + ">\n";
  159. }
  160. return "";
  161. }
  162. function downloadPage(page) {
  163. const link = document.createElement("a");
  164. document.body.appendChild(link);
  165. link.download = page.filename;
  166. link.href = page.url;
  167. link.dispatchEvent(new MouseEvent("click"));
  168. link.remove();
  169. }
  170. })();