download.js 1.0 KB

123456789101112131415161718192021222324252627
  1. import generate from "./generate.js"
  2. export default function download(selector) {
  3. document.querySelector(selector)?.addEventListener("submit", async function (e) {
  4. e.preventDefault()
  5. document.querySelector("#download").disabled = true
  6. const text = await generate()
  7. const filename = localStorage.getItem("contract_filename")+".php"
  8. downloadFile(filename, text)
  9. setTimeout(() => {
  10. document.querySelector("#download").disabled = false
  11. // e.preventDefault()
  12. }, 300)
  13. }, false)
  14. }
  15. // https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
  16. function downloadFile(filename, text) {
  17. let element = document.createElement('a')
  18. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text))
  19. element.setAttribute('download', filename)
  20. element.style.display = 'none'
  21. document.body.appendChild(element)
  22. element.click()
  23. document.body.removeChild(element)
  24. }