At what specific point should URL.revokeObjectURL be called?

14 hours ago 1
ARTICLE AD BOX
After the download completes

That's the only time you are sure no new blobPart will be fetched for the saving, and thus when the URL is not going to be used anymore.
However for simple <a download>, there is no event fired letting us know when this is the case, and apart from a hack involving a ServiceWorker to stream the data1, there is no safe way to know when the download is actually over.

For reference, Eli Grey's FileSaver.js (kind of the reference in terms of cross-browser support), uses a 40s delay after the anchor's click to revoke the URL.

1. If you want to go this route, then check Jimmy Warting's StreamSaver.js project.

Kaiido's user avatar

MDN is pretty straight forward on this

In order to prevent a resource leak, we must free the object URL with URL.revokeObjectURL() when it is no longer needed (that is, when the download has successfully started). Because the URL itself is just a string and therefore doesn't implement the disposable protocol, we cannot directly declare url with using; therefore, we create a DisposableStack to serve as the disposer for url. The object URL is revoked as soon as disposer goes out of scope, which is when either link.click() finishes or an error occurs somewhere.

However there is a tweak for a webextension

If you use URL.createObjectURL() to download data created in JavaScript and you want to revoke the object URL (with revokeObjectURL) later (as it is strongly recommended), you need to do that after the download has been completed. To do so, listen to the downloads.onChanged event.

Lastly be sure you do not need the object anymore

blob: URLs

Revoking the blob URL immediately after the image gets rendered would make the image unusable for user interactions (such as right-clicking to save the image or opening it in a new tab). For long-lived applications, you should revoke object URLs only when the resource is no longer accessible by the user (such as when the image is removed from the DOM).

mplungjan's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article