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. const legacyInfobarElement = document.querySelector("singlefile-infobar");
  87. if (legacyInfobarElement) {
  88. legacyInfobarElement.remove();
  89. }
  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. optionsAutoSave = message.options;
  99. if (document.readyState != "complete") {
  100. await new Promise(resolve => globalThis.addEventListener("load", resolve));
  101. }
  102. await autoSavePage();
  103. if (optionsAutoSave.autoSaveRepeat) {
  104. setTimeout(() => {
  105. if (autoSaveEnabled && !autoSavingPage) {
  106. pageAutoSaved = false;
  107. optionsAutoSave.autoSaveDelay = 0;
  108. onMessage(message);
  109. }
  110. }, optionsAutoSave.autoSaveRepeatDelay * 1000);
  111. }
  112. }
  113. async function autoSavePage() {
  114. const helper = singlefile.helper;
  115. if ((!autoSavingPage || autoSaveTimeout) && !pageAutoSaved) {
  116. autoSavingPage = true;
  117. if (optionsAutoSave.autoSaveDelay && !autoSaveTimeout) {
  118. await new Promise(resolve => autoSaveTimeout = setTimeout(resolve, optionsAutoSave.autoSaveDelay * 1000));
  119. await autoSavePage();
  120. } else {
  121. const waitForUserScript = window._singleFile_waitForUserScript;
  122. let frames = [];
  123. let framesSessionId;
  124. autoSaveTimeout = null;
  125. if (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  126. frames = await singlefile.processors.frameTree.getAsync(optionsAutoSave);
  127. }
  128. framesSessionId = frames && frames.sessionId;
  129. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  130. await waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  131. }
  132. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  133. savePage(docData, frames);
  134. if (framesSessionId) {
  135. singlefile.processors.frameTree.cleanup(framesSessionId);
  136. }
  137. helper.postProcessDoc(document, docData.markedElements, docData.invalidElements);
  138. if (optionsAutoSave.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 && optionsAutoSave && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveDiscard || optionsAutoSave.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" && optionsAutoSave.autoSaveDiscard) {
  161. autoSaveUnloadedPage({ autoSaveDiscard: optionsAutoSave.autoSaveDiscard });
  162. }
  163. }
  164. function onUnload() {
  165. if (!pageAutoSaved && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveRemove)) {
  166. autoSaveUnloadedPage({ autoSaveUnload: optionsAutoSave.autoSaveUnload, autoSaveRemove: optionsAutoSave.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 (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  174. frames = singlefile.processors.frameTree.getSync(optionsAutoSave);
  175. }
  176. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  177. waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  178. }
  179. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  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: optionsAutoSave.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. videos: docData.videos,
  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. 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. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  244. element.appendChild(templateElement);
  245. }
  246. });
  247. }