content-bootstrap.js 7.4 KB

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