content-bootstrap.js 9.2 KB

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