content.js 6.2 KB

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