content-bootstrap.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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.extension.core.content.bootstrap = this.extension.core.content.bootstrap || (() => {
  25. const singlefile = this.singlefile;
  26. const extension = this.extension;
  27. const MAX_CONTENT_SIZE = 32 * (1024 * 1024);
  28. let unloadListenerAdded, options, autoSaveEnabled, autoSaveTimeout, autoSavingPage, pageAutoSaved, previousLocationHref;
  29. extension.core.content.updatedResources = {};
  30. extension.core.content.visitDate = new Date();
  31. browser.runtime.sendMessage({ method: "autosave.init" }).then(message => {
  32. options = message.options;
  33. autoSaveEnabled = message.autoSaveEnabled;
  34. if (options && options.autoOpenEditor && detectSavedPage(document)) {
  35. if (document.readyState == "loading") {
  36. document.addEventListener("DOMContentLoaded", () => openEditor(document));
  37. } else {
  38. openEditor(document);
  39. }
  40. } else {
  41. refresh();
  42. }
  43. });
  44. browser.runtime.onMessage.addListener(message => {
  45. if ((autoSaveEnabled && message.method == "content.autosave") ||
  46. message.method == "content.maybeInit" ||
  47. message.method == "content.init" ||
  48. message.method == "content.openEditor" ||
  49. message.method == "devtools.resourceCommitted" ||
  50. message.method == "common.promptValueRequest") {
  51. return onMessage(message);
  52. }
  53. });
  54. document.addEventListener("DOMContentLoaded", init, false);
  55. return {};
  56. async function onMessage(message) {
  57. if (autoSaveEnabled && message.method == "content.autosave") {
  58. initAutoSavePage(message);
  59. return {};
  60. }
  61. if (message.method == "content.maybeInit") {
  62. init();
  63. return {};
  64. }
  65. if (message.method == "content.init") {
  66. options = message.options;
  67. autoSaveEnabled = message.autoSaveEnabled;
  68. refresh();
  69. return {};
  70. }
  71. if (message.method == "content.openEditor") {
  72. if (detectSavedPage(document)) {
  73. openEditor(document);
  74. } else {
  75. refresh();
  76. }
  77. return {};
  78. }
  79. if (message.method == "devtools.resourceCommitted") {
  80. extension.core.content.updatedResources[message.url] = { content: message.content, type: message.type, encoding: message.encoding };
  81. return {};
  82. }
  83. if (message.method == "common.promptValueRequest") {
  84. browser.runtime.sendMessage({ method: "tabs.promptValueResponse", value: prompt("SingleFile: " + message.promptMessage) });
  85. return {};
  86. }
  87. }
  88. function init() {
  89. if (previousLocationHref != location.href && !extension.core.processing) {
  90. pageAutoSaved = false;
  91. previousLocationHref = location.href;
  92. browser.runtime.sendMessage({ method: "tabs.init", savedPageDetected: detectSavedPage(document) });
  93. browser.runtime.sendMessage({ method: "ui.processInit" });
  94. }
  95. }
  96. async function initAutoSavePage(message) {
  97. options = message.options;
  98. if (document.readyState != "complete") {
  99. await new Promise(resolve => window.addEventListener("load", resolve));
  100. }
  101. await autoSavePage();
  102. if (options.autoSaveRepeat) {
  103. setTimeout(() => {
  104. if (autoSaveEnabled && !autoSavingPage) {
  105. pageAutoSaved = false;
  106. options.autoSaveDelay = 0;
  107. onMessage(message);
  108. }
  109. }, options.autoSaveRepeatDelay * 1000);
  110. }
  111. }
  112. async function autoSavePage() {
  113. const helper = singlefile.helper;
  114. if ((!autoSavingPage || autoSaveTimeout) && !pageAutoSaved) {
  115. autoSavingPage = true;
  116. if (options.autoSaveDelay && !autoSaveTimeout) {
  117. await new Promise(resolve => autoSaveTimeout = setTimeout(resolve, options.autoSaveDelay * 1000));
  118. await autoSavePage();
  119. } else {
  120. const waitForUserScript = window._singleFile_waitForUserScript;
  121. let frames = [];
  122. let framesSessionId;
  123. autoSaveTimeout = null;
  124. if (!options.removeFrames && window.frames && window.frames.length) {
  125. frames = await singlefile.processors.frameTree.getAsync(options);
  126. }
  127. framesSessionId = frames && frames.sessionId;
  128. if (options.userScriptEnabled && waitForUserScript) {
  129. await waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  130. }
  131. const docData = helper.preProcessDoc(document, window, options);
  132. savePage(docData, frames);
  133. if (framesSessionId) {
  134. singlefile.processors.frameTree.cleanup(framesSessionId);
  135. }
  136. helper.postProcessDoc(document, docData.markedElements);
  137. if (options.userScriptEnabled && waitForUserScript) {
  138. await waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
  139. }
  140. pageAutoSaved = true;
  141. autoSavingPage = false;
  142. }
  143. }
  144. }
  145. function refresh() {
  146. if (autoSaveEnabled && options && (options.autoSaveUnload || options.autoSaveLoadOrUnload)) {
  147. if (!unloadListenerAdded) {
  148. addEventListener("unload", onUnload);
  149. unloadListenerAdded = true;
  150. }
  151. } else {
  152. removeEventListener("unload", onUnload);
  153. unloadListenerAdded = false;
  154. }
  155. }
  156. function onUnload() {
  157. const helper = singlefile.helper;
  158. if (!pageAutoSaved || options.autoSaveUnload) {
  159. const waitForUserScript = window._singleFile_waitForUserScript;
  160. let frames = [];
  161. if (!options.removeFrames && window.frames && window.frames.length) {
  162. frames = singlefile.processors.frameTree.getSync(options);
  163. }
  164. if (options.userScriptEnabled && waitForUserScript) {
  165. waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  166. }
  167. const docData = helper.preProcessDoc(document, window, options);
  168. savePage(docData, frames);
  169. }
  170. }
  171. function savePage(docData, frames) {
  172. const helper = singlefile.helper;
  173. const updatedResources = extension.core.content.updatedResources;
  174. const visitDate = extension.core.content.visitDate.getTime();
  175. Object.keys(updatedResources).forEach(url => updatedResources[url].retrieved = false);
  176. browser.runtime.sendMessage({
  177. method: "autosave.save",
  178. taskId: options.taskId,
  179. content: helper.serialize(document),
  180. canvases: docData.canvases,
  181. fonts: docData.fonts,
  182. stylesheets: docData.stylesheets,
  183. images: docData.images,
  184. posters: docData.posters,
  185. usedFonts: docData.usedFonts,
  186. shadowRoots: docData.shadowRoots,
  187. imports: docData.imports,
  188. referrer: docData.referrer,
  189. frames: frames,
  190. url: location.href,
  191. updatedResources,
  192. visitDate
  193. });
  194. }
  195. async function openEditor(document) {
  196. const infobarElement = document.querySelector("singlefile-infobar");
  197. if (infobarElement) {
  198. infobarElement.remove();
  199. }
  200. serializeShadowRoots(document);
  201. const content = singlefile.helper.serialize(document);
  202. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < content.length; blockIndex++) {
  203. const message = {
  204. method: "editor.open",
  205. filename: decodeURIComponent(location.href.match(/^.*\/(.*)$/)[1])
  206. };
  207. message.truncated = content.length > MAX_CONTENT_SIZE;
  208. if (message.truncated) {
  209. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > content.length;
  210. message.content = content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  211. } else {
  212. message.content = content;
  213. }
  214. await browser.runtime.sendMessage(message);
  215. }
  216. }
  217. function detectSavedPage(document) {
  218. const helper = singlefile.helper;
  219. const firstDocumentChild = document.documentElement.firstChild;
  220. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  221. (firstDocumentChild.textContent.includes(helper.COMMENT_HEADER) || firstDocumentChild.textContent.includes(helper.COMMENT_HEADER_LEGACY));
  222. }
  223. function serializeShadowRoots(node) {
  224. const SHADOW_MODE_ATTRIBUTE_NAME = "shadowmode";
  225. node.querySelectorAll("*").forEach(element => {
  226. const shadowRoot = singlefile.helper.getShadowRoot(element);
  227. if (shadowRoot) {
  228. serializeShadowRoots(shadowRoot);
  229. const templateElement = document.createElement("template");
  230. templateElement.setAttribute(SHADOW_MODE_ATTRIBUTE_NAME, "open");
  231. templateElement.appendChild(shadowRoot);
  232. element.appendChild(templateElement);
  233. }
  234. });
  235. }
  236. })();