content-bootstrap.js 7.7 KB

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