Search code examples
javascriptrevokeobjecturl

Way to know when an ObjectUrl has been downloaded (to revoke it...)


I would like to delete my Blobs once they are download by the user:

var url = window.URL.createObjectURL(myBlob);           
var a = document.createElement("a");
a.download = 'myFile' + fileExtension;
a.href = url;
a.click();//download launched

/** Here i want to revoke the ObjectURL and delete my Blob, but i dunno when? **/

Can i do this without using a dummy timer?


Solution

  • To simply revoke the URL when the blob has been accessed, use a click event handler.

    a.onclick = function () {
        window.URL.revokeObjectURL(url);
    };
    

    To check that the blob has actually been downloaded, you will need to download it via XHR where you can monitor its download progress using progress and load events. As far as I know you cannot monitor download progress in JavaScript for something initiated outside of XHR.

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress