1
0

content-bootstrap.js 8.7 KB

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