content-bootstrap.js 8.0 KB

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