1
0

content.js 6.4 KB

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