downloader.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. export class downloader {
  2. #name;
  3. #content;
  4. #type;
  5. #encode;
  6. constructor() {
  7. this.#name = "download.json";
  8. this.#content = "";
  9. this.#type = "text/plain";
  10. this.#encode = "utf-8";
  11. }
  12. name(target) {
  13. this.#name = target;
  14. return this;
  15. }
  16. content(target) {
  17. this.#content = target;
  18. return this;
  19. }
  20. type(target) {
  21. this.#type = target;
  22. return this;
  23. }
  24. encode(target) {
  25. this.#encode = target;
  26. return this;
  27. }
  28. get #href() {
  29. return (
  30. "data:" + this.#type
  31. + ";charset=" + this.#encode + ","
  32. + encodeURIComponent(this.#content)
  33. );
  34. }
  35. get #link() {
  36. const link = document.createElement("a");
  37. link.style.display = "none";
  38. link.href = this.#href;
  39. link.download = this.#name;
  40. return link;
  41. }
  42. process() {
  43. const link = this.#link;
  44. const body = document.querySelector("body");
  45. body.appendChild(link);
  46. link.click();
  47. body.removeChild(link);
  48. return this;
  49. }
  50. }