content.js 5.1 KB

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