download.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. let filename = page.filename.replace(/[/\\?%*:|"<>\x7F]+/g, "_");
  44. if (filename.length > 128) {
  45. filename = filename.replace(/\.html?$/, "").substring(0, 122) + "….html";
  46. }
  47. const downloadInfo = {
  48. url: page.url,
  49. saveAs: options.confirmFilename,
  50. filename
  51. };
  52. if (options.incognito) {
  53. downloadInfo.incognito = true;
  54. }
  55. const downloadId = await browser.downloads.download(downloadInfo);
  56. return new Promise((resolve, reject) => {
  57. browser.downloads.onChanged.addListener(onChanged);
  58. function onChanged(event) {
  59. if (event.id == downloadId && event.state) {
  60. if (event.state.current == "complete") {
  61. URL.revokeObjectURL(page.url);
  62. resolve({});
  63. browser.downloads.onChanged.removeListener(onChanged);
  64. }
  65. if (event.state.current == "interrupted") {
  66. URL.revokeObjectURL(page.url);
  67. reject(new Error(event.state.current));
  68. browser.downloads.onChanged.removeListener(onChanged);
  69. }
  70. }
  71. }
  72. });
  73. }
  74. })();