content-bootstrap.js 7.6 KB

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