content-bootstrap.js 7.9 KB

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