Why does my blob file save the entire web page and not the entered string?

I have this function taking a line and I want people to be able to load a text file consisting of this line. However, whenever I click the link, the downloaded file simply consists of the entire HTML page instead of a line.

JS:

function downloadFile(names) {
  var text = names.toString();
  $('#downloadlink').href = createFile(text);
}

function createFile(text) {
  var data = new Blob([text], {type: 'text/plain'});

  if (textFile !== null) {
    window.URL.revokeObjectURL(textFile);
  }

  var textFile = window.URL.createObjectURL(data);

  return textFile;
}

HTML:

<a download="colors.txt" href="" id="downloadlink">Download</a>

Why is he doing this? Am I building Blob wrong? How to fix it?

+4
source share
2 answers

, jQuery , , $('#downloadlink'). jQuery $ jQuery, , . , id () , jQuery .

- $('#stuff').href. jQuery attr() :

$('downloadLink').attr('href', createFile(text));

jQuery, , $.

JSBin.

+5

href . $(document).ready :

window.addEventListener("load", function()
{
    document.getElementById('downloadlink').href = window.URL.createObjectURL(new Blob(["content"], {type: 'text/plain'}));
});
+1

Source: https://habr.com/ru/post/1628654/


All Articles