content-bootstrap.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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;
  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.autoOpenEditor) {
  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") || message.method == "content.init" || message.method == "devtools.resourceCommitted" || message.method == "common.promptValueRequest") {
  44. return onMessage(message);
  45. }
  46. });
  47. browser.runtime.sendMessage({ method: "tabs.init" });
  48. browser.runtime.sendMessage({ method: "ui.processInit" });
  49. return {};
  50. async function onMessage(message) {
  51. if (autoSaveEnabled && message.method == "content.autosave") {
  52. initAutoSavePage(message);
  53. return {};
  54. }
  55. if (message.method == "content.init") {
  56. options = message.options;
  57. autoSaveEnabled = message.autoSaveEnabled;
  58. refresh();
  59. return {};
  60. }
  61. if (message.method == "devtools.resourceCommitted") {
  62. singlefile.extension.core.content.updatedResources[message.url] = { content: message.content, type: message.type, encoding: message.encoding };
  63. return {};
  64. }
  65. if (message.method == "common.promptValueRequest") {
  66. browser.runtime.sendMessage({ method: "tabs.promptValueResponse", value: prompt("SingleFile: " + message.promptMessage) });
  67. return {};
  68. }
  69. }
  70. async function initAutoSavePage(message) {
  71. options = message.options;
  72. if (document.readyState != "complete") {
  73. await new Promise(resolve => window.addEventListener("load", resolve));
  74. }
  75. await autoSavePage();
  76. if (options.autoSaveRepeat) {
  77. setTimeout(() => {
  78. if (autoSaveEnabled && !autoSavingPage) {
  79. pageAutoSaved = false;
  80. options.autoSaveDelay = 0;
  81. onMessage(message);
  82. }
  83. }, options.autoSaveRepeatDelay * 1000);
  84. }
  85. }
  86. async function autoSavePage() {
  87. const helper = singlefile.lib.helper;
  88. if ((!autoSavingPage || autoSaveTimeout) && !pageAutoSaved) {
  89. autoSavingPage = true;
  90. if (options.autoSaveDelay && !autoSaveTimeout) {
  91. await new Promise(resolve => autoSaveTimeout = setTimeout(resolve, options.autoSaveDelay * 1000));
  92. await autoSavePage();
  93. } else {
  94. let frames = [];
  95. autoSaveTimeout = null;
  96. if (!options.removeFrames && singlefile.lib.processors.frameTree.content.frames && window.frames && window.frames.length) {
  97. frames = await singlefile.lib.processors.frameTree.content.frames.getAsync(options);
  98. }
  99. if (options.userScriptEnabled && helper.waitForUserScript) {
  100. await helper.waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  101. }
  102. const docData = helper.preProcessDoc(document, window, options);
  103. savePage(docData, frames);
  104. helper.postProcessDoc(document, docData.markedElements);
  105. if (options.userScriptEnabled && helper.waitForUserScript) {
  106. await helper.waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
  107. }
  108. pageAutoSaved = true;
  109. autoSavingPage = false;
  110. }
  111. }
  112. }
  113. function refresh() {
  114. if (autoSaveEnabled && options && (options.autoSaveUnload || options.autoSaveLoadOrUnload)) {
  115. if (!unloadListenerAdded) {
  116. addEventListener("unload", onUnload);
  117. unloadListenerAdded = true;
  118. }
  119. } else {
  120. removeEventListener("unload", onUnload);
  121. unloadListenerAdded = false;
  122. }
  123. }
  124. function onUnload() {
  125. const helper = singlefile.lib.helper;
  126. if (!pageAutoSaved || options.autoSaveUnload) {
  127. let frames = [];
  128. if (!options.removeFrames && singlefile.lib.processors.frameTree.content.frames && window.frames && window.frames.length) {
  129. frames = singlefile.lib.processors.frameTree.content.frames.getSync(options);
  130. }
  131. if (options.userScriptEnabled && helper.waitForUserScript) {
  132. helper.waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  133. }
  134. const docData = helper.preProcessDoc(document, window, options);
  135. savePage(docData, frames);
  136. }
  137. }
  138. function savePage(docData, frames) {
  139. const helper = singlefile.lib.helper;
  140. const updatedResources = singlefile.extension.core.content.updatedResources;
  141. Object.keys(updatedResources).forEach(url => updatedResources[url].retrieved = false);
  142. browser.runtime.sendMessage({
  143. method: "autosave.save",
  144. taskId: options.taskId,
  145. content: helper.serialize(document),
  146. canvases: docData.canvases,
  147. fonts: docData.fonts,
  148. stylesheets: docData.stylesheets,
  149. images: docData.images,
  150. posters: docData.posters,
  151. usedFonts: docData.usedFonts,
  152. shadowRoots: docData.shadowRoots,
  153. imports: docData.imports,
  154. referrer: docData.referrer,
  155. frames: frames,
  156. url: location.href,
  157. updatedResources
  158. });
  159. }
  160. async function openEditor(document) {
  161. if (document.documentElement.firstChild.nodeType == Node.COMMENT_NODE && document.documentElement.firstChild.textContent.includes("Page saved with SingleFile")) {
  162. serializeShadowRoots(document);
  163. const content = singlefile.lib.modules.serializer.process(document);
  164. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < content.length; blockIndex++) {
  165. const message = {
  166. method: "editor.open",
  167. filename: decodeURIComponent(location.href.match(/^.*\/(.*)$/)[1])
  168. };
  169. message.truncated = content.length > MAX_CONTENT_SIZE;
  170. if (message.truncated) {
  171. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > content.length;
  172. message.content = content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  173. } else {
  174. message.content = content;
  175. }
  176. await browser.runtime.sendMessage(message);
  177. }
  178. } else {
  179. refresh();
  180. }
  181. }
  182. function serializeShadowRoots(node) {
  183. const SHADOW_MODE_ATTRIBUTE_NAME = "shadowmode";
  184. node.querySelectorAll("*").forEach(element => {
  185. if (element.shadowRoot) {
  186. serializeShadowRoots(element.shadowRoot);
  187. const templateElement = document.createElement("template");
  188. templateElement.setAttribute(SHADOW_MODE_ATTRIBUTE_NAME, "open");
  189. templateElement.appendChild(element.shadowRoot);
  190. element.appendChild(templateElement);
  191. }
  192. });
  193. }
  194. })();