content-bootstrap.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global browser, window, addEventListener, removeEventListener, document, location, setTimeout, prompt, Node */
  24. this.singlefile.extension.core.content.bootstrap = this.singlefile.extension.core.content.bootstrap || (() => {
  25. const singlefile = this.singlefile;
  26. const MAX_CONTENT_SIZE = 32 * (1024 * 1024);
  27. let unloadListenerAdded, options, autoSaveEnabled, autoSaveTimeout, autoSavingPage, pageAutoSaved, previousLocationHref;
  28. singlefile.extension.core.content.updatedResources = {};
  29. singlefile.extension.core.content.visitDate = new Date();
  30. browser.runtime.sendMessage({ method: "autosave.init" }).then(message => {
  31. options = message.options;
  32. autoSaveEnabled = message.autoSaveEnabled;
  33. if (options && options.autoOpenEditor && detectSavedPage(document)) {
  34. if (document.readyState == "loading") {
  35. document.addEventListener("DOMContentLoaded", () => openEditor(document));
  36. } else {
  37. openEditor(document);
  38. }
  39. } else {
  40. refresh();
  41. }
  42. });
  43. browser.runtime.onMessage.addListener(message => {
  44. if ((autoSaveEnabled && message.method == "content.autosave") ||
  45. message.method == "content.maybeInit" ||
  46. message.method == "content.init" ||
  47. message.method == "content.openEditor" ||
  48. message.method == "devtools.resourceCommitted" ||
  49. message.method == "common.promptValueRequest") {
  50. return onMessage(message);
  51. }
  52. });
  53. document.addEventListener("DOMContentLoaded", init, false);
  54. return {};
  55. async function onMessage(message) {
  56. if (autoSaveEnabled && message.method == "content.autosave") {
  57. initAutoSavePage(message);
  58. return {};
  59. }
  60. if (message.method == "content.maybeInit") {
  61. init();
  62. return {};
  63. }
  64. if (message.method == "content.init") {
  65. options = message.options;
  66. autoSaveEnabled = message.autoSaveEnabled;
  67. refresh();
  68. return {};
  69. }
  70. if (message.method == "content.openEditor") {
  71. if (detectSavedPage(document)) {
  72. openEditor(document);
  73. } else {
  74. refresh();
  75. }
  76. return {};
  77. }
  78. if (message.method == "devtools.resourceCommitted") {
  79. singlefile.extension.core.content.updatedResources[message.url] = { content: message.content, type: message.type, encoding: message.encoding };
  80. return {};
  81. }
  82. if (message.method == "common.promptValueRequest") {
  83. browser.runtime.sendMessage({ method: "tabs.promptValueResponse", value: prompt("SingleFile: " + message.promptMessage) });
  84. return {};
  85. }
  86. }
  87. function init() {
  88. if (previousLocationHref != location.href && !singlefile.extension.core.processing) {
  89. pageAutoSaved = false;
  90. previousLocationHref = location.href;
  91. browser.runtime.sendMessage({ method: "tabs.init", savedPageDetected: detectSavedPage(document) });
  92. browser.runtime.sendMessage({ method: "ui.processInit" });
  93. }
  94. }
  95. async function initAutoSavePage(message) {
  96. options = message.options;
  97. if (document.readyState != "complete") {
  98. await new Promise(resolve => window.addEventListener("load", resolve));
  99. }
  100. await autoSavePage();
  101. if (options.autoSaveRepeat) {
  102. setTimeout(() => {
  103. if (autoSaveEnabled && !autoSavingPage) {
  104. pageAutoSaved = false;
  105. options.autoSaveDelay = 0;
  106. onMessage(message);
  107. }
  108. }, options.autoSaveRepeatDelay * 1000);
  109. }
  110. }
  111. async function autoSavePage() {
  112. const helper = singlefile.lib.helper;
  113. if ((!autoSavingPage || autoSaveTimeout) && !pageAutoSaved) {
  114. autoSavingPage = true;
  115. if (options.autoSaveDelay && !autoSaveTimeout) {
  116. await new Promise(resolve => autoSaveTimeout = setTimeout(resolve, options.autoSaveDelay * 1000));
  117. await autoSavePage();
  118. } else {
  119. let frames = [];
  120. let framesSessionId;
  121. autoSaveTimeout = null;
  122. if (!options.removeFrames && singlefile.lib.processors.frameTree.content.frames && window.frames && window.frames.length) {
  123. frames = await singlefile.lib.processors.frameTree.content.frames.getAsync(options);
  124. }
  125. framesSessionId = frames && frames.sessionId;
  126. if (options.userScriptEnabled && helper.waitForUserScript) {
  127. await helper.waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  128. }
  129. const docData = helper.preProcessDoc(document, window, options);
  130. savePage(docData, frames);
  131. if (framesSessionId) {
  132. singlefile.lib.processors.frameTree.content.frames.cleanup(framesSessionId);
  133. }
  134. helper.postProcessDoc(document, docData.markedElements);
  135. if (options.userScriptEnabled && helper.waitForUserScript) {
  136. await helper.waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
  137. }
  138. pageAutoSaved = true;
  139. autoSavingPage = false;
  140. }
  141. }
  142. }
  143. function refresh() {
  144. if (autoSaveEnabled && options && (options.autoSaveUnload || options.autoSaveLoadOrUnload)) {
  145. if (!unloadListenerAdded) {
  146. addEventListener("unload", onUnload);
  147. unloadListenerAdded = true;
  148. }
  149. } else {
  150. removeEventListener("unload", onUnload);
  151. unloadListenerAdded = false;
  152. }
  153. }
  154. function onUnload() {
  155. const helper = singlefile.lib.helper;
  156. if (!pageAutoSaved || options.autoSaveUnload) {
  157. let frames = [];
  158. if (!options.removeFrames && singlefile.lib.processors.frameTree.content.frames && window.frames && window.frames.length) {
  159. frames = singlefile.lib.processors.frameTree.content.frames.getSync(options);
  160. }
  161. if (options.userScriptEnabled && helper.waitForUserScript) {
  162. helper.waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  163. }
  164. const docData = helper.preProcessDoc(document, window, options);
  165. savePage(docData, frames);
  166. }
  167. }
  168. function savePage(docData, frames) {
  169. const helper = singlefile.lib.helper;
  170. const updatedResources = singlefile.extension.core.content.updatedResources;
  171. const visitDate = singlefile.extension.core.content.visitDate.getTime();
  172. Object.keys(updatedResources).forEach(url => updatedResources[url].retrieved = false);
  173. browser.runtime.sendMessage({
  174. method: "autosave.save",
  175. taskId: options.taskId,
  176. content: helper.serialize(document),
  177. canvases: docData.canvases,
  178. fonts: docData.fonts,
  179. stylesheets: docData.stylesheets,
  180. images: docData.images,
  181. posters: docData.posters,
  182. usedFonts: docData.usedFonts,
  183. shadowRoots: docData.shadowRoots,
  184. imports: docData.imports,
  185. referrer: docData.referrer,
  186. frames: frames,
  187. url: location.href,
  188. updatedResources,
  189. visitDate
  190. });
  191. }
  192. async function openEditor(document) {
  193. const infobarElement = document.querySelector("singlefile-infobar");
  194. if (infobarElement) {
  195. infobarElement.remove();
  196. }
  197. serializeShadowRoots(document);
  198. const content = singlefile.lib.modules.serializer.process(document);
  199. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < content.length; blockIndex++) {
  200. const message = {
  201. method: "editor.open",
  202. filename: decodeURIComponent(location.href.match(/^.*\/(.*)$/)[1])
  203. };
  204. message.truncated = content.length > MAX_CONTENT_SIZE;
  205. if (message.truncated) {
  206. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > content.length;
  207. message.content = content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  208. } else {
  209. message.content = content;
  210. }
  211. await browser.runtime.sendMessage(message);
  212. }
  213. }
  214. function detectSavedPage(document) {
  215. const helper = singlefile.lib.helper;
  216. const firstDocumentChild = document.documentElement.firstChild;
  217. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  218. (firstDocumentChild.textContent.includes(helper.COMMENT_HEADER) || firstDocumentChild.textContent.includes(helper.COMMENT_HEADER_LEGACY));
  219. }
  220. function serializeShadowRoots(node) {
  221. const SHADOW_MODE_ATTRIBUTE_NAME = "shadowmode";
  222. node.querySelectorAll("*").forEach(element => {
  223. const shadowRoot = singlefile.lib.helper.getShadowRoot(element);
  224. if (shadowRoot) {
  225. serializeShadowRoots(shadowRoot);
  226. const templateElement = document.createElement("template");
  227. templateElement.setAttribute(SHADOW_MODE_ATTRIBUTE_NAME, "open");
  228. templateElement.appendChild(shadowRoot);
  229. element.appendChild(templateElement);
  230. }
  231. });
  232. }
  233. })();