javascript download string as file 1

javascript download string as file

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

Here is what the above code is Doing:
1. It creates a new element
2. It sets the href attribute to the data URI
3. It sets the download attribute to the filename
4. It sets the display to none
5. It appends the element to the body
6. It clicks the element
7. It removes the element from the body

Similar Posts