content.js 5.0 KB

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