download.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global browser, singlefile, Blob */
  21. singlefile.download = (() => {
  22. browser.runtime.onMessage.addListener((request, sender) => {
  23. if (request.download) {
  24. try {
  25. if (request.content) {
  26. request.url = URL.createObjectURL(new Blob([request.content], { type: "text/html" }));
  27. }
  28. return downloadPage(request, { confirmFilename: request.confirmFilename, incognito: sender.tab.incognito })
  29. .catch(error => {
  30. if (error.message && error.message.includes("'incognito'")) {
  31. return downloadPage(request, { confirmFilename: request.confirmFilename });
  32. } else {
  33. return { notSupported: true };
  34. }
  35. });
  36. } catch (error) {
  37. return Promise.resolve({ notSupported: true });
  38. }
  39. }
  40. });
  41. return { downloadPage };
  42. async function downloadPage(page, options) {
  43. const downloadInfo = {
  44. url: page.url,
  45. saveAs: options.confirmFilename,
  46. filename: page.filename
  47. };
  48. if (options.incognito) {
  49. downloadInfo.incognito = true;
  50. }
  51. const downloadId = await browser.downloads.download(downloadInfo);
  52. return new Promise((resolve, reject) => {
  53. browser.downloads.onChanged.addListener(onChanged);
  54. function onChanged(event) {
  55. if (event.id == downloadId && event.state) {
  56. if (event.state.current == "complete") {
  57. URL.revokeObjectURL(page.url);
  58. resolve({});
  59. browser.downloads.onChanged.removeListener(onChanged);
  60. }
  61. if (event.state.current == "interrupted" && (!event.error || event.error.current != "USER_CANCELED")) {
  62. URL.revokeObjectURL(page.url);
  63. reject(new Error(event.state.current));
  64. browser.downloads.onChanged.removeListener(onChanged);
  65. }
  66. }
  67. }
  68. });
  69. }
  70. })();