content-bootstrap.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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, globalThis, window, document, location, setTimeout, XMLHttpRequest, Node, DOMParser */
  24. const MAX_CONTENT_SIZE = 32 * (1024 * 1024);
  25. const singlefile = globalThis.singlefileBootstrap;
  26. const pendingResponses = new Map();
  27. let unloadListenerAdded, optionsAutoSave, tabId, tabIndex, autoSaveEnabled, autoSaveTimeout, autoSavingPage, pageAutoSaved, previousLocationHref, savedPageDetected, compressContent, extractDataFromPageTags, insertTextBody;
  28. singlefile.pageInfo = {
  29. updatedResources: {},
  30. visitDate: new Date()
  31. };
  32. browser.runtime.sendMessage({ method: "bootstrap.init" }).then(message => {
  33. optionsAutoSave = message.optionsAutoSave;
  34. const options = message.options;
  35. tabId = message.tabId;
  36. tabIndex = message.tabIndex;
  37. autoSaveEnabled = message.autoSaveEnabled;
  38. if (options && options.autoOpenEditor && detectSavedPage(document)) {
  39. if (document.readyState == "loading") {
  40. document.addEventListener("DOMContentLoaded", () => openEditor(document));
  41. } else {
  42. openEditor(document);
  43. }
  44. } else {
  45. if (document.readyState == "loading") {
  46. document.addEventListener("DOMContentLoaded", refresh);
  47. } else {
  48. refresh();
  49. }
  50. }
  51. });
  52. browser.runtime.onMessage.addListener(message => {
  53. if ((autoSaveEnabled && message.method == "content.autosave") ||
  54. message.method == "content.maybeInit" ||
  55. message.method == "content.init" ||
  56. message.method == "content.openEditor" ||
  57. message.method == "devtools.resourceCommitted" ||
  58. message.method == "singlefile.fetchResponse") {
  59. return onMessage(message);
  60. }
  61. });
  62. document.addEventListener("DOMContentLoaded", init, false);
  63. if (globalThis.window == globalThis.top && location && location.href && (location.href.startsWith("file://") || location.href.startsWith("content://"))) {
  64. if (document.readyState == "loading") {
  65. document.addEventListener("DOMContentLoaded", extractFile, false);
  66. } else {
  67. extractFile();
  68. }
  69. }
  70. async function extractFile() {
  71. debugger;
  72. if (document.documentElement.dataset.sfz !== undefined) {
  73. const data = await getContent();
  74. document.querySelectorAll("#sfz-error-message").forEach(element => element.remove());
  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 = "(()=>{" +
  110. "document.currentScript.remove();" +
  111. "if (document.readyState=='complete') {run()} else {globalThis.addEventListener('load', run)}" +
  112. "function run() {this.bootstrap([" + (new Uint8Array(data)).toString() + "])}" +
  113. "})()";
  114. document.body.appendChild(scriptElement);
  115. }
  116. async function onMessage(message) {
  117. if (autoSaveEnabled && message.method == "content.autosave") {
  118. initAutoSavePage(message);
  119. return {};
  120. }
  121. if (message.method == "content.maybeInit") {
  122. init();
  123. return {};
  124. }
  125. if (message.method == "content.init") {
  126. optionsAutoSave = message.options;
  127. autoSaveEnabled = message.autoSaveEnabled;
  128. refresh();
  129. return {};
  130. }
  131. if (message.method == "content.openEditor") {
  132. if (detectSavedPage(document)) {
  133. openEditor(document);
  134. } else {
  135. refresh();
  136. }
  137. return {};
  138. }
  139. if (message.method == "devtools.resourceCommitted") {
  140. singlefile.pageInfo.updatedResources[message.url] = { content: message.content, type: message.type, encoding: message.encoding };
  141. return {};
  142. }
  143. if (message.method == "singlefile.fetchResponse") {
  144. return await onFetchResponse(message);
  145. }
  146. }
  147. async function onFetchResponse(message) {
  148. const pendingResponse = pendingResponses.get(message.requestId);
  149. if (pendingResponse) {
  150. if (message.error) {
  151. pendingResponse.reject(new Error(message.error));
  152. pendingResponses.delete(message.requestId);
  153. } else {
  154. if (message.truncated) {
  155. if (pendingResponse.array) {
  156. pendingResponse.array = pendingResponse.array.concat(message.array);
  157. } else {
  158. pendingResponse.array = message.array;
  159. pendingResponses.set(message.requestId, pendingResponse);
  160. }
  161. if (message.finished) {
  162. message.array = pendingResponse.array;
  163. }
  164. }
  165. if (!message.truncated || message.finished) {
  166. pendingResponse.resolve(message.array);
  167. pendingResponses.delete(message.requestId);
  168. }
  169. }
  170. return {};
  171. }
  172. }
  173. function init() {
  174. const legacyInfobarElement = document.querySelector("singlefile-infobar");
  175. if (legacyInfobarElement) {
  176. legacyInfobarElement.remove();
  177. }
  178. if (previousLocationHref != location.href && !singlefile.pageInfo.processing) {
  179. pageAutoSaved = false;
  180. previousLocationHref = location.href;
  181. browser.runtime.sendMessage({ method: "tabs.init", savedPageDetected: detectSavedPage(document) }).catch(() => { });
  182. browser.runtime.sendMessage({ method: "ui.processInit" }).catch(() => { });
  183. }
  184. }
  185. async function initAutoSavePage(message) {
  186. optionsAutoSave = message.options;
  187. if (document.readyState != "complete") {
  188. await new Promise(resolve => globalThis.addEventListener("load", resolve));
  189. }
  190. await autoSavePage();
  191. if (optionsAutoSave.autoSaveRepeat) {
  192. setTimeout(() => {
  193. if (autoSaveEnabled && !autoSavingPage) {
  194. pageAutoSaved = false;
  195. optionsAutoSave.autoSaveDelay = 0;
  196. onMessage(message);
  197. }
  198. }, optionsAutoSave.autoSaveRepeatDelay * 1000);
  199. }
  200. }
  201. async function autoSavePage() {
  202. const helper = singlefile.helper;
  203. if ((!autoSavingPage || autoSaveTimeout) && !pageAutoSaved) {
  204. autoSavingPage = true;
  205. if (optionsAutoSave.autoSaveDelay && !autoSaveTimeout) {
  206. await new Promise(resolve => autoSaveTimeout = setTimeout(resolve, optionsAutoSave.autoSaveDelay * 1000));
  207. await autoSavePage();
  208. } else {
  209. const waitForUserScript = window[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
  210. let frames = [];
  211. let framesSessionId;
  212. autoSaveTimeout = null;
  213. if (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  214. frames = await singlefile.processors.frameTree.getAsync(optionsAutoSave);
  215. }
  216. framesSessionId = frames && frames.sessionId;
  217. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  218. await waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  219. }
  220. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  221. savePage(docData, frames);
  222. if (framesSessionId) {
  223. singlefile.processors.frameTree.cleanup(framesSessionId);
  224. }
  225. helper.postProcessDoc(document, docData.markedElements, docData.invalidElements);
  226. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  227. await waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
  228. }
  229. pageAutoSaved = true;
  230. autoSavingPage = false;
  231. }
  232. }
  233. }
  234. function refresh() {
  235. if (autoSaveEnabled && optionsAutoSave && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveDiscard || optionsAutoSave.autoSaveRemove)) {
  236. if (!unloadListenerAdded) {
  237. globalThis.addEventListener("unload", onUnload);
  238. document.addEventListener("visibilitychange", onVisibilityChange);
  239. unloadListenerAdded = true;
  240. }
  241. } else {
  242. globalThis.removeEventListener("unload", onUnload);
  243. document.removeEventListener("visibilitychange", onVisibilityChange);
  244. unloadListenerAdded = false;
  245. }
  246. }
  247. function onVisibilityChange() {
  248. if (document.visibilityState == "hidden" && optionsAutoSave.autoSaveDiscard) {
  249. autoSaveUnloadedPage({ autoSaveDiscard: optionsAutoSave.autoSaveDiscard });
  250. }
  251. }
  252. function onUnload() {
  253. if (!pageAutoSaved && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveRemove)) {
  254. autoSaveUnloadedPage({ autoSaveUnload: optionsAutoSave.autoSaveUnload, autoSaveRemove: optionsAutoSave.autoSaveRemove });
  255. }
  256. }
  257. function autoSaveUnloadedPage({ autoSaveUnload, autoSaveDiscard, autoSaveRemove }) {
  258. const helper = singlefile.helper;
  259. const waitForUserScript = window[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
  260. let frames = [];
  261. if (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  262. frames = singlefile.processors.frameTree.getSync(optionsAutoSave);
  263. }
  264. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  265. waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  266. }
  267. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  268. savePage(docData, frames, { autoSaveUnload, autoSaveDiscard, autoSaveRemove });
  269. }
  270. function savePage(docData, frames, { autoSaveUnload, autoSaveDiscard, autoSaveRemove } = {}) {
  271. const helper = singlefile.helper;
  272. const updatedResources = singlefile.pageInfo.updatedResources;
  273. const visitDate = singlefile.pageInfo.visitDate.getTime();
  274. Object.keys(updatedResources).forEach(url => updatedResources[url].retrieved = false);
  275. browser.runtime.sendMessage({
  276. method: "autosave.save",
  277. tabId,
  278. tabIndex,
  279. taskId: optionsAutoSave.taskId,
  280. content: helper.serialize(document),
  281. canvases: docData.canvases,
  282. fonts: docData.fonts,
  283. stylesheets: docData.stylesheets,
  284. images: docData.images,
  285. posters: docData.posters,
  286. usedFonts: docData.usedFonts,
  287. shadowRoots: docData.shadowRoots,
  288. videos: docData.videos,
  289. referrer: docData.referrer,
  290. adoptedStyleSheets: docData.adoptedStyleSheets,
  291. frames: frames,
  292. url: location.href,
  293. updatedResources,
  294. visitDate,
  295. autoSaveUnload,
  296. autoSaveDiscard,
  297. autoSaveRemove
  298. });
  299. }
  300. async function openEditor(document) {
  301. let content;
  302. if (compressContent) {
  303. content = await getContent();
  304. } else {
  305. serializeShadowRoots(document);
  306. content = singlefile.helper.serialize(document);
  307. }
  308. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < content.length; blockIndex++) {
  309. const message = {
  310. method: "editor.open",
  311. filename: decodeURIComponent(location.href.match(/^.*\/(.*)$/)[1]),
  312. compressContent,
  313. extractDataFromPageTags,
  314. insertTextBody,
  315. selfExtractingArchive: compressContent
  316. };
  317. message.truncated = content.length > MAX_CONTENT_SIZE;
  318. if (message.truncated) {
  319. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > content.length;
  320. if (content instanceof Uint8Array) {
  321. message.content = Array.from(content.subarray(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE));
  322. } else {
  323. message.content = content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  324. }
  325. } else {
  326. message.content = content instanceof Uint8Array ? Array.from(content) : content;
  327. }
  328. await browser.runtime.sendMessage(message);
  329. }
  330. }
  331. function detectSavedPage(document) {
  332. if (savedPageDetected === undefined) {
  333. const helper = singlefile.helper;
  334. const firstDocumentChild = document.documentElement.firstChild;
  335. compressContent = document.documentElement.dataset.sfz == "";
  336. extractDataFromPageTags = Boolean(document.querySelector("sfz-extra-data"));
  337. insertTextBody = Boolean(document.querySelector("body > main[hidden]"));
  338. savedPageDetected = compressContent || (
  339. firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  340. (firstDocumentChild.textContent.includes(helper.COMMENT_HEADER) || firstDocumentChild.textContent.includes(helper.COMMENT_HEADER_LEGACY)));
  341. }
  342. return savedPageDetected;
  343. }
  344. function serializeShadowRoots(node) {
  345. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  346. node.querySelectorAll("*").forEach(element => {
  347. const shadowRoot = singlefile.helper.getShadowRoot(element);
  348. if (shadowRoot) {
  349. serializeShadowRoots(shadowRoot);
  350. const templateElement = document.createElement("template");
  351. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  352. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  353. element.appendChild(templateElement);
  354. }
  355. });
  356. }