仅在下载对象URL后,如何才能撤消该对象URL? [英] How can I revoke an object URL only after it's downloaded?

查看:49
本文介绍了仅在下载对象URL后,如何才能撤消该对象URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在JavaScript中保存文件:

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();

下载文件后,我想撤消URL(使用URL.revokeObjectURL).何时安全这样做?

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

我可以在调用 a.click()后立即将其撤消吗(这似乎可行,但我不确定它是否安全)?在 a 的click事件监听器中?有没有办法让点击事件监听器在默认操作之后 运行?

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?

推荐答案

a.click()模拟该元素的单击,而不是传播click事件,因此它是直接发送到浏览器.我相信使用计时器将撤销URL对象的撤销转移到另一个事件周期会更安全一些:

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);

这篇关于仅在下载对象URL后,如何才能撤消该对象URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆