content.js 5.2 KB

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