content-bootstrap.js 9.3 KB

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