How can I revoke an object URL only after it's downloaded?

寵の児 提交于 2021-02-07 14:21:47

问题


I'm saving a file in JavaScript using the following code:

var a = document.createElement('a');
a.href = URL.createObjectURL(new Blob(['SOME DATA']));
a.download = 'some.dat';
a.click();

I want to revoke the URL (using URL.revokeObjectURL) once the file is downloaded. When is it safe to do so?

Can I revoke it immediately after calling a.click() (which seems to work, but I'm not sure it's safe)? In a's click event listener? Is there a way to make a click event listener run after the default action?


回答1:


a.click() on a DOM element simulates a click on the element, instead of propagation of the click event, so it's directly sent to the browser. I believe it would be a little bit safer to move revoking of URL object to another event cycle using a timer:

setTimeout(function() {
 URL.revokeObjectURL(a.href);
}, 0);


来源:https://stackoverflow.com/questions/37240551/how-can-i-revoke-an-object-url-only-after-its-downloaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!