The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Save Browser Text To A File And Download It

TODO: Pull subtitle into page object html_start_default_section html_end_default_section script_start_default_section script_end_default_section

notes

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Save Browser Text To A File And Download It

This is what I'm using to save text
from a web page and download it
to a file

-- html/
-- title: HTML Source
-- show

<button id="trigger">
  Save Text To File 
</button>

-- /html

-- script/
-- title: Script Source
-- show

const doDownload = () => {
  const data = new Blob(
    ["some text"], 
    { type: "application/octet-stream" }
  )
  const link = document.createElement("a")
  link.href = URL.createObjectURL(data)
  link.setAttribute("download", "your-file-name.txt");
  link.click()
}

document.addEventListener("DOMContentLoaded", () => {
  trigger.addEventListener("click", doDownload)
})


-- /script


-- notes
-- title: notes

- Replace the `"some text"`` in the Blob creation
array with whatever should actually be downloaded. 
I'm pulling that from an `.innerText`` call in my
live versions

- I use `application/octet-stream`` to trigger
the download from the browser. Using `text/plain``
instead would show the text in the browser window
and let the user download manually from there

- The filename of the download is set by changing 
`your-file-name.txt`` which can be set dynamically
in the script

- There's a `URL.revokeObjectURL(link.href)`` call 
that can be added after `link.click()`` to release 
the object. The documentation on it is a little
unclear so I'm leaving it off


-- ref
-- title: JavaScript Blob
-- subtitle: MDN
-- link: https://developer.mozilla.org/en-US/docs/Web/API/Blob

-- ref
-- title: URL: revokeObjectURL()
-- subtitle: MDN
-- url: https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL_static

-- categories
-- JavaScript 
-- WebDev 

-- metadata
-- date: 2023-08-12 20:02:08
-- id: 2tufcdmu
-- site: aws
-- type: post
-- status: draft