Search code examples
htmldownloadanchor

Detect HTML anchor tag download selection


I use an anchor tag to provide my users with an option to download some client side generated data in a file. I use the following code:

function GenerateTextFile (FileType, FileName, FileContents)
{
var data = new Blob ([FileContents], {type: 'text/plain'});
var url = window.URL.createObjectURL (data);
var link = document.createElement ("a");
link.download  = FileName + "." + FileType ;
link.href      = url ;
link.innerText = " Click here to download" ;
};

Later on I invoke the following to tidy up :

window.URL.revokeObjectURL (url);

Please can someone tell me how I can detect that the user has clicked on the anchor tag? I would like to either remove or change the text so that the download is not activated twice.


Solution

  • You can add a click listener to the link. Or is there some reason you don’t want that?

    link.onclick = function(){console.log("link was clicked");}