Is possible to save JavaScript variable as file? [duplicate]

Yes it is, you could do something like this in HTML5, using the download attribute

function download_txt() {
  var textToSave = document.getElementById('txt').innerHTML;
  var hiddenElement = document.createElement('a');

  hiddenElement.href="https://stackoverflow.com/questions/24898044/data:attachment/text," + encodeURI(textToSave);
  hiddenElement.target="_blank";
  hiddenElement.download = 'myFile.txt';
  hiddenElement.click();
}

document.getElementById('test').addEventListener('click', download_txt);

FIDDLE

Leave a Comment