single-file-extension-bootstrap.js 15 KB

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