content-bootstrap.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. let frames = [];
  121. let framesSessionId;
  122. autoSaveTimeout = null;
  123. if (!options.removeFrames && window.frames && window.frames.length) {
  124. frames = await singlefile.processors.frameTree.getAsync(options);
  125. }
  126. framesSessionId = frames && frames.sessionId;
  127. if (options.userScriptEnabled && helper.waitForUserScript.callback) {
  128. await helper.waitForUserScript.callback(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  129. }
  130. const docData = helper.preProcessDoc(document, window, options);
  131. savePage(docData, frames);
  132. if (framesSessionId) {
  133. singlefile.processors.frameTree.cleanup(framesSessionId);
  134. }
  135. helper.postProcessDoc(document, docData.markedElements);
  136. if (options.userScriptEnabled && helper.waitForUserScript.callback) {
  137. await helper.waitForUserScript.callback(helper.ON_AFTER_CAPTURE_EVENT_NAME);
  138. }
  139. pageAutoSaved = true;
  140. autoSavingPage = false;
  141. }
  142. }
  143. }
  144. function refresh() {
  145. if (autoSaveEnabled && options && (options.autoSaveUnload || options.autoSaveLoadOrUnload)) {
  146. if (!unloadListenerAdded) {
  147. addEventListener("unload", onUnload);
  148. unloadListenerAdded = true;
  149. }
  150. } else {
  151. removeEventListener("unload", onUnload);
  152. unloadListenerAdded = false;
  153. }
  154. }
  155. function onUnload() {
  156. const helper = singlefile.helper;
  157. if (!pageAutoSaved || options.autoSaveUnload) {
  158. let frames = [];
  159. if (!options.removeFrames && window.frames && window.frames.length) {
  160. frames = singlefile.processors.frameTree.getSync(options);
  161. }
  162. if (options.userScriptEnabled && helper.waitForUserScript.callback) {
  163. helper.waitForUserScript.callback(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  164. }
  165. const docData = helper.preProcessDoc(document, window, options);
  166. savePage(docData, frames);
  167. }
  168. }
  169. function savePage(docData, frames) {
  170. const helper = singlefile.helper;
  171. const updatedResources = extension.core.content.updatedResources;
  172. const visitDate = extension.core.content.visitDate.getTime();
  173. Object.keys(updatedResources).forEach(url => updatedResources[url].retrieved = false);
  174. browser.runtime.sendMessage({
  175. method: "autosave.save",
  176. taskId: options.taskId,
  177. content: helper.serialize(document),
  178. canvases: docData.canvases,
  179. fonts: docData.fonts,
  180. stylesheets: docData.stylesheets,
  181. images: docData.images,
  182. posters: docData.posters,
  183. usedFonts: docData.usedFonts,
  184. shadowRoots: docData.shadowRoots,
  185. imports: docData.imports,
  186. referrer: docData.referrer,
  187. frames: frames,
  188. url: location.href,
  189. updatedResources,
  190. visitDate
  191. });
  192. }
  193. async function openEditor(document) {
  194. const infobarElement = document.querySelector("singlefile-infobar");
  195. if (infobarElement) {
  196. infobarElement.remove();
  197. }
  198. serializeShadowRoots(document);
  199. const content = singlefile.helper.serialize(document);
  200. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < content.length; blockIndex++) {
  201. const message = {
  202. method: "editor.open",
  203. filename: decodeURIComponent(location.href.match(/^.*\/(.*)$/)[1])
  204. };
  205. message.truncated = content.length > MAX_CONTENT_SIZE;
  206. if (message.truncated) {
  207. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > content.length;
  208. message.content = content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  209. } else {
  210. message.content = content;
  211. }
  212. await browser.runtime.sendMessage(message);
  213. }
  214. }
  215. function detectSavedPage(document) {
  216. const helper = singlefile.helper;
  217. const firstDocumentChild = document.documentElement.firstChild;
  218. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  219. (firstDocumentChild.textContent.includes(helper.COMMENT_HEADER) || firstDocumentChild.textContent.includes(helper.COMMENT_HEADER_LEGACY));
  220. }
  221. function serializeShadowRoots(node) {
  222. const SHADOW_MODE_ATTRIBUTE_NAME = "shadowmode";
  223. node.querySelectorAll("*").forEach(element => {
  224. const shadowRoot = singlefile.helper.getShadowRoot(element);
  225. if (shadowRoot) {
  226. serializeShadowRoots(shadowRoot);
  227. const templateElement = document.createElement("template");
  228. templateElement.setAttribute(SHADOW_MODE_ATTRIBUTE_NAME, "open");
  229. templateElement.appendChild(shadowRoot);
  230. element.appendChild(templateElement);
  231. }
  232. });
  233. }
  234. })();