content.js 7.1 KB

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