single-file-extension-bootstrap.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. (function () {
  2. 'use strict';
  3. /*
  4. * Copyright 2010-2020 Gildas Lormeau
  5. * contact : gildas.lormeau <at> gmail.com
  6. *
  7. * This file is part of SingleFile.
  8. *
  9. * The code in this file is free software: you can redistribute it and/or
  10. * modify it under the terms of the GNU Affero General Public License
  11. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  12. * of the License, or (at your option) any later version.
  13. *
  14. * The code in this file is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  17. * General Public License for more details.
  18. *
  19. * As additional permission under GNU AGPL version 3 section 7, you may
  20. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  21. * AGPL normally required by section 4, provided you include this license
  22. * notice and a URL through which recipients can access the Corresponding
  23. * Source.
  24. */
  25. /* global browser, globalThis, window, document, location, setTimeout, XMLHttpRequest, Node, DOMParser */
  26. const MAX_CONTENT_SIZE = 32 * (1024 * 1024);
  27. const singlefile = globalThis.singlefileBootstrap;
  28. const pendingResponses = new Map();
  29. let unloadListenerAdded, optionsAutoSave, tabId, tabIndex, autoSaveEnabled, autoSaveTimeout, autoSavingPage, pageAutoSaved, previousLocationHref, savedPageDetected, compressContent, extractDataFromPageTags, insertTextBody;
  30. singlefile.pageInfo = {
  31. updatedResources: {},
  32. visitDate: new Date()
  33. };
  34. browser.runtime.sendMessage({ method: "bootstrap.init" }).then(message => {
  35. optionsAutoSave = message.optionsAutoSave;
  36. const options = message.options;
  37. tabId = message.tabId;
  38. tabIndex = message.tabIndex;
  39. autoSaveEnabled = message.autoSaveEnabled;
  40. if (options && options.autoOpenEditor && detectSavedPage(document)) {
  41. if (document.readyState == "loading") {
  42. document.addEventListener("DOMContentLoaded", () => openEditor(document));
  43. } else {
  44. openEditor(document);
  45. }
  46. } else {
  47. if (document.readyState == "loading") {
  48. document.addEventListener("DOMContentLoaded", refresh);
  49. } else {
  50. refresh();
  51. }
  52. }
  53. });
  54. browser.runtime.onMessage.addListener(message => {
  55. if ((autoSaveEnabled && message.method == "content.autosave") ||
  56. message.method == "content.maybeInit" ||
  57. message.method == "content.init" ||
  58. message.method == "content.openEditor" ||
  59. message.method == "devtools.resourceCommitted" ||
  60. message.method == "singlefile.fetchResponse") {
  61. return onMessage(message);
  62. }
  63. });
  64. document.addEventListener("DOMContentLoaded", init, false);
  65. if (globalThis.window == globalThis.top && location && location.href && (location.href.startsWith("file://") || location.href.startsWith("content://"))) {
  66. if (document.readyState == "loading") {
  67. document.addEventListener("DOMContentLoaded", extractFile, false);
  68. } else {
  69. extractFile();
  70. }
  71. }
  72. async function extractFile() {
  73. if (document.documentElement.dataset.sfz !== undefined) {
  74. const data = await getContent();
  75. executeBootstrap(data);
  76. } else {
  77. if ((document.body && document.body.childNodes.length == 1 && document.body.childNodes[0].tagName == "PRE" && /<html[^>]* data-sfz[^>]*>/i.test(document.body.childNodes[0].textContent))) {
  78. const doc = (new DOMParser()).parseFromString(document.body.childNodes[0].textContent, "text/html");
  79. document.replaceChild(doc.documentElement, document.documentElement);
  80. document.querySelectorAll("script").forEach(element => {
  81. const scriptElement = document.createElement("script");
  82. scriptElement.textContent = element.textContent;
  83. element.parentElement.replaceChild(scriptElement, element);
  84. });
  85. await extractFile();
  86. }
  87. }
  88. }
  89. function getContent() {
  90. return new Promise((resolve, reject) => {
  91. const xhr = new XMLHttpRequest();
  92. xhr.open("GET", location.href);
  93. xhr.send();
  94. xhr.responseType = "arraybuffer";
  95. xhr.onload = () => resolve(new Uint8Array(xhr.response));
  96. xhr.onerror = () => {
  97. const errorMessageElement = document.getElementById("sfz-error-message");
  98. if (errorMessageElement) {
  99. errorMessageElement.remove();
  100. }
  101. const requestId = pendingResponses.size;
  102. pendingResponses.set(requestId, { resolve, reject });
  103. browser.runtime.sendMessage({ method: "singlefile.fetch", requestId, url: location.href });
  104. };
  105. });
  106. }
  107. function executeBootstrap(data) {
  108. const scriptElement = document.createElement("script");
  109. scriptElement.textContent = "(() => { document.currentScript.remove(); const bootstrapReady = this.bootstrap && this.bootstrap([" + (new Uint8Array(data)).toString() + "]); if (bootstrapReady) { bootstrapReady.then(() => document.dispatchEvent(new CustomEvent(\"single-file-display-infobar\"))); } })()";
  110. document.body.appendChild(scriptElement);
  111. }
  112. async function onMessage(message) {
  113. if (autoSaveEnabled && message.method == "content.autosave") {
  114. initAutoSavePage(message);
  115. return {};
  116. }
  117. if (message.method == "content.maybeInit") {
  118. init();
  119. return {};
  120. }
  121. if (message.method == "content.init") {
  122. optionsAutoSave = message.options;
  123. autoSaveEnabled = message.autoSaveEnabled;
  124. refresh();
  125. return {};
  126. }
  127. if (message.method == "content.openEditor") {
  128. if (detectSavedPage(document)) {
  129. openEditor(document);
  130. } else {
  131. refresh();
  132. }
  133. return {};
  134. }
  135. if (message.method == "devtools.resourceCommitted") {
  136. singlefile.pageInfo.updatedResources[message.url] = { content: message.content, type: message.type, encoding: message.encoding };
  137. return {};
  138. }
  139. if (message.method == "singlefile.fetchResponse") {
  140. return await onFetchResponse(message);
  141. }
  142. }
  143. async function onFetchResponse(message) {
  144. const pendingResponse = pendingResponses.get(message.requestId);
  145. if (pendingResponse) {
  146. if (message.error) {
  147. pendingResponse.reject(new Error(message.error));
  148. pendingResponses.delete(message.requestId);
  149. } else {
  150. if (message.truncated) {
  151. if (pendingResponse.array) {
  152. pendingResponse.array = pendingResponse.array.concat(message.array);
  153. } else {
  154. pendingResponse.array = message.array;
  155. pendingResponses.set(message.requestId, pendingResponse);
  156. }
  157. if (message.finished) {
  158. message.array = pendingResponse.array;
  159. }
  160. }
  161. if (!message.truncated || message.finished) {
  162. pendingResponse.resolve(message.array);
  163. pendingResponses.delete(message.requestId);
  164. }
  165. }
  166. return {};
  167. }
  168. }
  169. function init() {
  170. const legacyInfobarElement = document.querySelector("singlefile-infobar");
  171. if (legacyInfobarElement) {
  172. legacyInfobarElement.remove();
  173. }
  174. if (previousLocationHref != location.href && !singlefile.pageInfo.processing) {
  175. pageAutoSaved = false;
  176. previousLocationHref = location.href;
  177. browser.runtime.sendMessage({ method: "tabs.init", savedPageDetected: detectSavedPage(document) }).catch(() => { });
  178. browser.runtime.sendMessage({ method: "ui.processInit" }).catch(() => { });
  179. }
  180. }
  181. async function initAutoSavePage(message) {
  182. optionsAutoSave = message.options;
  183. if (document.readyState != "complete") {
  184. await new Promise(resolve => globalThis.addEventListener("load", resolve));
  185. }
  186. await autoSavePage();
  187. if (optionsAutoSave.autoSaveRepeat) {
  188. setTimeout(() => {
  189. if (autoSaveEnabled && !autoSavingPage) {
  190. pageAutoSaved = false;
  191. optionsAutoSave.autoSaveDelay = 0;
  192. onMessage(message);
  193. }
  194. }, optionsAutoSave.autoSaveRepeatDelay * 1000);
  195. }
  196. }
  197. async function autoSavePage() {
  198. const helper = singlefile.helper;
  199. if ((!autoSavingPage || autoSaveTimeout) && !pageAutoSaved) {
  200. autoSavingPage = true;
  201. if (optionsAutoSave.autoSaveDelay && !autoSaveTimeout) {
  202. await new Promise(resolve => autoSaveTimeout = setTimeout(resolve, optionsAutoSave.autoSaveDelay * 1000));
  203. await autoSavePage();
  204. } else {
  205. const waitForUserScript = window[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
  206. let frames = [];
  207. let framesSessionId;
  208. autoSaveTimeout = null;
  209. if (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  210. frames = await singlefile.processors.frameTree.getAsync(optionsAutoSave);
  211. }
  212. framesSessionId = frames && frames.sessionId;
  213. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  214. await waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  215. }
  216. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  217. savePage(docData, frames);
  218. if (framesSessionId) {
  219. singlefile.processors.frameTree.cleanup(framesSessionId);
  220. }
  221. helper.postProcessDoc(document, docData.markedElements, docData.invalidElements);
  222. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  223. await waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
  224. }
  225. pageAutoSaved = true;
  226. autoSavingPage = false;
  227. }
  228. }
  229. }
  230. function refresh() {
  231. if (autoSaveEnabled && optionsAutoSave && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveDiscard || optionsAutoSave.autoSaveRemove)) {
  232. if (!unloadListenerAdded) {
  233. globalThis.addEventListener("unload", onUnload);
  234. document.addEventListener("visibilitychange", onVisibilityChange);
  235. unloadListenerAdded = true;
  236. }
  237. } else {
  238. globalThis.removeEventListener("unload", onUnload);
  239. document.removeEventListener("visibilitychange", onVisibilityChange);
  240. unloadListenerAdded = false;
  241. }
  242. }
  243. function onVisibilityChange() {
  244. if (document.visibilityState == "hidden" && optionsAutoSave.autoSaveDiscard) {
  245. autoSaveUnloadedPage({ autoSaveDiscard: optionsAutoSave.autoSaveDiscard });
  246. }
  247. }
  248. function onUnload() {
  249. if (!pageAutoSaved && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveRemove)) {
  250. autoSaveUnloadedPage({ autoSaveUnload: optionsAutoSave.autoSaveUnload, autoSaveRemove: optionsAutoSave.autoSaveRemove });
  251. }
  252. }
  253. function autoSaveUnloadedPage({ autoSaveUnload, autoSaveDiscard, autoSaveRemove }) {
  254. const helper = singlefile.helper;
  255. const waitForUserScript = window[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
  256. let frames = [];
  257. if (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  258. frames = singlefile.processors.frameTree.getSync(optionsAutoSave);
  259. }
  260. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  261. waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  262. }
  263. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  264. savePage(docData, frames, { autoSaveUnload, autoSaveDiscard, autoSaveRemove });
  265. }
  266. function savePage(docData, frames, { autoSaveUnload, autoSaveDiscard, autoSaveRemove } = {}) {
  267. const helper = singlefile.helper;
  268. const updatedResources = singlefile.pageInfo.updatedResources;
  269. const visitDate = singlefile.pageInfo.visitDate.getTime();
  270. Object.keys(updatedResources).forEach(url => updatedResources[url].retrieved = false);
  271. browser.runtime.sendMessage({
  272. method: "autosave.save",
  273. tabId,
  274. tabIndex,
  275. taskId: optionsAutoSave.taskId,
  276. content: helper.serialize(document),
  277. canvases: docData.canvases,
  278. fonts: docData.fonts,
  279. stylesheets: docData.stylesheets,
  280. images: docData.images,
  281. posters: docData.posters,
  282. usedFonts: docData.usedFonts,
  283. shadowRoots: docData.shadowRoots,
  284. videos: docData.videos,
  285. referrer: docData.referrer,
  286. adoptedStyleSheets: docData.adoptedStyleSheets,
  287. frames: frames,
  288. url: location.href,
  289. updatedResources,
  290. visitDate,
  291. autoSaveUnload,
  292. autoSaveDiscard,
  293. autoSaveRemove
  294. });
  295. }
  296. async function openEditor(document) {
  297. let content;
  298. if (compressContent) {
  299. content = await getContent();
  300. } else {
  301. serializeShadowRoots(document);
  302. content = singlefile.helper.serialize(document);
  303. }
  304. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < content.length; blockIndex++) {
  305. const message = {
  306. method: "editor.open",
  307. filename: decodeURIComponent(location.href.match(/^.*\/(.*)$/)[1]),
  308. compressContent,
  309. extractDataFromPageTags,
  310. insertTextBody,
  311. selfExtractingArchive: compressContent
  312. };
  313. message.truncated = content.length > MAX_CONTENT_SIZE;
  314. if (message.truncated) {
  315. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > content.length;
  316. if (content instanceof Uint8Array) {
  317. message.content = Array.from(content.subarray(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE));
  318. } else {
  319. message.content = content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  320. }
  321. } else {
  322. message.content = content instanceof Uint8Array ? Array.from(content) : content;
  323. }
  324. await browser.runtime.sendMessage(message);
  325. }
  326. }
  327. function detectSavedPage(document) {
  328. if (savedPageDetected === undefined) {
  329. const helper = singlefile.helper;
  330. const firstDocumentChild = document.documentElement.firstChild;
  331. compressContent = document.documentElement.dataset.sfz == "";
  332. extractDataFromPageTags = Boolean(document.querySelector("sfz-extra-data"));
  333. insertTextBody = Boolean(document.querySelector("body > main[hidden]"));
  334. savedPageDetected = compressContent || (
  335. firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  336. (firstDocumentChild.textContent.includes(helper.COMMENT_HEADER) || firstDocumentChild.textContent.includes(helper.COMMENT_HEADER_LEGACY)));
  337. }
  338. return savedPageDetected;
  339. }
  340. function serializeShadowRoots(node) {
  341. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  342. node.querySelectorAll("*").forEach(element => {
  343. const shadowRoot = singlefile.helper.getShadowRoot(element);
  344. if (shadowRoot) {
  345. serializeShadowRoots(shadowRoot);
  346. const templateElement = document.createElement("template");
  347. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  348. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  349. element.appendChild(templateElement);
  350. }
  351. });
  352. }
  353. })();