content.js 4.9 KB

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