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