content-bootstrap.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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, 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. if (document.documentElement.dataset.sfz !== undefined) {
  72. const data = await getContent();
  73. document.querySelectorAll("#sfz-error-message").forEach(element => element.remove());
  74. executeBootstrap(data);
  75. } else {
  76. if ((document.body && document.body.childNodes.length == 1 && document.body.childNodes[0].tagName == "PRE" && /<html[^>]* data-sfz[^>]*>/i.test(document.body.childNodes[0].textContent))) {
  77. const doc = (new DOMParser()).parseFromString(document.body.childNodes[0].textContent, "text/html");
  78. document.replaceChild(doc.documentElement, document.documentElement);
  79. document.querySelectorAll("script").forEach(element => {
  80. const scriptElement = document.createElement("script");
  81. scriptElement.textContent = element.textContent;
  82. element.parentElement.replaceChild(scriptElement, element);
  83. });
  84. await extractFile();
  85. }
  86. }
  87. }
  88. function getContent() {
  89. return new Promise((resolve, reject) => {
  90. const xhr = new XMLHttpRequest();
  91. xhr.open("GET", location.href);
  92. xhr.send();
  93. xhr.responseType = "arraybuffer";
  94. xhr.onload = () => resolve(new Uint8Array(xhr.response));
  95. xhr.onerror = () => {
  96. const errorMessageElement = document.getElementById("sfz-error-message");
  97. if (errorMessageElement) {
  98. errorMessageElement.remove();
  99. }
  100. const requestId = pendingResponses.size;
  101. pendingResponses.set(requestId, { resolve, reject });
  102. browser.runtime.sendMessage({ method: "singlefile.fetch", requestId, url: location.href });
  103. };
  104. });
  105. }
  106. function executeBootstrap(data) {
  107. const scriptElement = document.createElement("script");
  108. scriptElement.textContent = "(()=>{" +
  109. "document.currentScript.remove();" +
  110. "if (document.readyState=='complete') {run()} else {globalThis.addEventListener('load', run)}" +
  111. "function run() {this.bootstrap([" + (new Uint8Array(data)).toString() + "])}" +
  112. "})()";
  113. document.body.appendChild(scriptElement);
  114. }
  115. async function onMessage(message) {
  116. if (autoSaveEnabled && message.method == "content.autosave") {
  117. initAutoSavePage(message);
  118. return {};
  119. }
  120. if (message.method == "content.maybeInit") {
  121. init();
  122. return {};
  123. }
  124. if (message.method == "content.init") {
  125. optionsAutoSave = message.options;
  126. autoSaveEnabled = message.autoSaveEnabled;
  127. refresh();
  128. return {};
  129. }
  130. if (message.method == "content.openEditor") {
  131. if (detectSavedPage(document)) {
  132. openEditor(document);
  133. } else {
  134. refresh();
  135. }
  136. return {};
  137. }
  138. if (message.method == "devtools.resourceCommitted") {
  139. singlefile.pageInfo.updatedResources[message.url] = { content: message.content, type: message.type, encoding: message.encoding };
  140. return {};
  141. }
  142. if (message.method == "singlefile.fetchResponse") {
  143. return await onFetchResponse(message);
  144. }
  145. }
  146. async function onFetchResponse(message) {
  147. const pendingResponse = pendingResponses.get(message.requestId);
  148. if (pendingResponse) {
  149. if (message.error) {
  150. pendingResponse.reject(new Error(message.error));
  151. pendingResponses.delete(message.requestId);
  152. } else {
  153. if (message.truncated) {
  154. if (pendingResponse.array) {
  155. pendingResponse.array = pendingResponse.array.concat(message.array);
  156. } else {
  157. pendingResponse.array = message.array;
  158. pendingResponses.set(message.requestId, pendingResponse);
  159. }
  160. if (message.finished) {
  161. message.array = pendingResponse.array;
  162. }
  163. }
  164. if (!message.truncated || message.finished) {
  165. pendingResponse.resolve(message.array);
  166. pendingResponses.delete(message.requestId);
  167. }
  168. }
  169. return {};
  170. }
  171. }
  172. function init() {
  173. const legacyInfobarElement = document.querySelector("singlefile-infobar");
  174. if (legacyInfobarElement) {
  175. legacyInfobarElement.remove();
  176. }
  177. if (previousLocationHref != location.href && !singlefile.pageInfo.processing) {
  178. pageAutoSaved = false;
  179. previousLocationHref = location.href;
  180. browser.runtime.sendMessage({ method: "tabs.init", savedPageDetected: detectSavedPage(document) }).catch(() => { });
  181. browser.runtime.sendMessage({ method: "ui.processInit" }).catch(() => { });
  182. }
  183. }
  184. async function initAutoSavePage(message) {
  185. optionsAutoSave = message.options;
  186. if (document.readyState != "complete") {
  187. await new Promise(resolve => globalThis.addEventListener("load", resolve));
  188. }
  189. await autoSavePage();
  190. if (optionsAutoSave.autoSaveRepeat) {
  191. setTimeout(() => {
  192. if (autoSaveEnabled && !autoSavingPage) {
  193. pageAutoSaved = false;
  194. optionsAutoSave.autoSaveDelay = 0;
  195. onMessage(message);
  196. }
  197. }, optionsAutoSave.autoSaveRepeatDelay * 1000);
  198. }
  199. }
  200. async function autoSavePage() {
  201. const helper = singlefile.helper;
  202. if ((!autoSavingPage || autoSaveTimeout) && !pageAutoSaved) {
  203. autoSavingPage = true;
  204. if (optionsAutoSave.autoSaveDelay && !autoSaveTimeout) {
  205. await new Promise(resolve => autoSaveTimeout = setTimeout(resolve, optionsAutoSave.autoSaveDelay * 1000));
  206. await autoSavePage();
  207. } else {
  208. const waitForUserScript = globalThis[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
  209. let frames = [];
  210. let framesSessionId;
  211. autoSaveTimeout = null;
  212. if (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  213. frames = await singlefile.processors.frameTree.getAsync(optionsAutoSave);
  214. }
  215. framesSessionId = frames && frames.sessionId;
  216. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  217. await waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  218. }
  219. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  220. savePage(docData, frames);
  221. if (framesSessionId) {
  222. singlefile.processors.frameTree.cleanup(framesSessionId);
  223. }
  224. helper.postProcessDoc(document, docData.markedElements, docData.invalidElements);
  225. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  226. await waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
  227. }
  228. pageAutoSaved = true;
  229. autoSavingPage = false;
  230. }
  231. }
  232. }
  233. function refresh() {
  234. if (autoSaveEnabled && optionsAutoSave && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveDiscard || optionsAutoSave.autoSaveRemove)) {
  235. if (!unloadListenerAdded) {
  236. globalThis.addEventListener("unload", onUnload);
  237. document.addEventListener("visibilitychange", onVisibilityChange);
  238. unloadListenerAdded = true;
  239. }
  240. } else {
  241. globalThis.removeEventListener("unload", onUnload);
  242. document.removeEventListener("visibilitychange", onVisibilityChange);
  243. unloadListenerAdded = false;
  244. }
  245. }
  246. function onVisibilityChange() {
  247. if (document.visibilityState == "hidden" && optionsAutoSave.autoSaveDiscard) {
  248. autoSaveUnloadedPage({ autoSaveDiscard: optionsAutoSave.autoSaveDiscard });
  249. }
  250. }
  251. function onUnload() {
  252. if (!pageAutoSaved && (optionsAutoSave.autoSaveUnload || optionsAutoSave.autoSaveLoadOrUnload || optionsAutoSave.autoSaveRemove)) {
  253. autoSaveUnloadedPage({ autoSaveUnload: optionsAutoSave.autoSaveUnload, autoSaveRemove: optionsAutoSave.autoSaveRemove });
  254. }
  255. }
  256. function autoSaveUnloadedPage({ autoSaveUnload, autoSaveDiscard, autoSaveRemove }) {
  257. const helper = singlefile.helper;
  258. const waitForUserScript = globalThis[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
  259. let frames = [];
  260. if (!optionsAutoSave.removeFrames && globalThis.frames && globalThis.frames.length) {
  261. frames = singlefile.processors.frameTree.getSync(optionsAutoSave);
  262. }
  263. if (optionsAutoSave.userScriptEnabled && waitForUserScript) {
  264. waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
  265. }
  266. const docData = helper.preProcessDoc(document, globalThis, optionsAutoSave);
  267. savePage(docData, frames, { autoSaveUnload, autoSaveDiscard, autoSaveRemove });
  268. }
  269. function savePage(docData, frames, { autoSaveUnload, autoSaveDiscard, autoSaveRemove } = {}) {
  270. const helper = singlefile.helper;
  271. const updatedResources = singlefile.pageInfo.updatedResources;
  272. const visitDate = singlefile.pageInfo.visitDate.getTime();
  273. Object.keys(updatedResources).forEach(url => updatedResources[url].retrieved = false);
  274. browser.runtime.sendMessage({
  275. method: "autosave.save",
  276. tabId,
  277. tabIndex,
  278. taskId: optionsAutoSave.taskId,
  279. content: helper.serialize(document),
  280. canvases: docData.canvases,
  281. fonts: docData.fonts,
  282. stylesheets: docData.stylesheets,
  283. images: docData.images,
  284. posters: docData.posters,
  285. usedFonts: docData.usedFonts,
  286. shadowRoots: docData.shadowRoots,
  287. videos: docData.videos,
  288. referrer: docData.referrer,
  289. adoptedStyleSheets: docData.adoptedStyleSheets,
  290. frames: frames,
  291. url: location.href,
  292. updatedResources,
  293. visitDate,
  294. autoSaveUnload,
  295. autoSaveDiscard,
  296. autoSaveRemove
  297. });
  298. }
  299. async function openEditor(document) {
  300. let content;
  301. if (compressContent) {
  302. content = await getContent();
  303. } else {
  304. serializeShadowRoots(document);
  305. content = singlefile.helper.serialize(document);
  306. }
  307. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < content.length; blockIndex++) {
  308. const message = {
  309. method: "editor.open",
  310. filename: decodeURIComponent(location.href.match(/^.*\/(.*)$/)[1]),
  311. compressContent,
  312. extractDataFromPageTags,
  313. insertTextBody,
  314. selfExtractingArchive: compressContent
  315. };
  316. message.truncated = content.length > MAX_CONTENT_SIZE;
  317. if (message.truncated) {
  318. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > content.length;
  319. if (content instanceof Uint8Array) {
  320. message.content = Array.from(content.subarray(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE));
  321. } else {
  322. message.content = content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  323. }
  324. } else {
  325. message.content = content instanceof Uint8Array ? Array.from(content) : content;
  326. }
  327. await browser.runtime.sendMessage(message);
  328. }
  329. }
  330. function detectSavedPage(document) {
  331. if (savedPageDetected === undefined) {
  332. const helper = singlefile.helper;
  333. const firstDocumentChild = document.documentElement.firstChild;
  334. compressContent = document.documentElement.dataset.sfz == "";
  335. extractDataFromPageTags = Boolean(document.querySelector("sfz-extra-data"));
  336. insertTextBody = Boolean(document.querySelector("body > main[hidden]"));
  337. savedPageDetected = compressContent || (
  338. firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  339. (firstDocumentChild.textContent.includes(helper.COMMENT_HEADER) || firstDocumentChild.textContent.includes(helper.COMMENT_HEADER_LEGACY)));
  340. }
  341. return savedPageDetected;
  342. }
  343. function serializeShadowRoots(node) {
  344. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  345. node.querySelectorAll("*").forEach(element => {
  346. const shadowRoot = singlefile.helper.getShadowRoot(element);
  347. if (shadowRoot) {
  348. serializeShadowRoots(shadowRoot);
  349. const templateElement = document.createElement("template");
  350. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  351. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  352. element.appendChild(templateElement);
  353. }
  354. });
  355. }