Skip to content

Instantly share code, notes, and snippets.

@kocisov
Created June 9, 2018 16:00
Show Gist options
  • Select an option

  • Save kocisov/30f984e7a64653fb59058f69a96c90bc to your computer and use it in GitHub Desktop.

Select an option

Save kocisov/30f984e7a64653fb59058f69a96c90bc to your computer and use it in GitHub Desktop.

Revisions

  1. kocisov created this gist Jun 9, 2018.
    22 changes: 22 additions & 0 deletions download.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    function download(filename, text) {
    // create link element
    const element = document.createElement('a')

    // set link href to our text
    element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`)

    // set attribute download
    element.setAttribute('download', filename)

    // make element invisible
    element.style.display = 'none'

    // add element to the DOM
    document.body.appendChild(element)

    // simulate click
    element.click()

    // and remove element from the DOM
    document.body.removeChild(element)
    }