content.js 8.0 KB

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