content.js 6.1 KB

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