download.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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, URL */
  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, conflictAction: request.conflictAction })
  29. .catch(error => {
  30. if (error.message && error.message.includes("'incognito'")) {
  31. return downloadPage(request, { confirmFilename: request.confirmFilename, conflictAction: request.conflictAction });
  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. conflictAction: options.conflictAction
  48. };
  49. if (options.incognito) {
  50. downloadInfo.incognito = true;
  51. }
  52. const downloadId = await browser.downloads.download(downloadInfo);
  53. return new Promise((resolve, reject) => {
  54. browser.downloads.onChanged.addListener(onChanged);
  55. function onChanged(event) {
  56. if (event.id == downloadId && event.state) {
  57. if (event.state.current == "complete") {
  58. URL.revokeObjectURL(page.url);
  59. resolve({});
  60. browser.downloads.onChanged.removeListener(onChanged);
  61. }
  62. if (event.state.current == "interrupted" && (!event.error || event.error.current != "USER_CANCELED")) {
  63. URL.revokeObjectURL(page.url);
  64. reject(new Error(event.state.current));
  65. browser.downloads.onChanged.removeListener(onChanged);
  66. }
  67. }
  68. }
  69. });
  70. }
  71. })();