Browser / Javascript - Object URL (createObjectURL / revokeObjectURL)

About

The ObjectUrl is an object that represents the data URL strings.

Example

The javascript browser api function URL.createObjectURL creates an ObjectUrl that represents a data uri that can then be passed as URL.

Example to download a text file:

let textBlob = new Blob( ["Hello World !"], { type: 'text/plain' });
  • Create the ObjectUrl
let objectUrl = URL.createObjectURL(textBlob);
  • Create the anchor with its download attribute
let a = document.createElement("a");
document.body.append(a);
a.href=objectUrl;
let fileName = "hello-world.txt";
a.setAttribute("download",fileName);
a.innerText = `Download ${fileName}`;
// To prevent memory leaks, always revoke the URL after the download.
a.addEventListener('click', (e) => {
    setTimeout(() => URL.revokeObjectURL(e.target.href), 30 * 1000);
});
  • Result:

Management

createObjectURL

You can create a ObjectURL with the URL function URL.createObjectURL()

const objectURL = URL.createObjectURL(object)

where: the object parameter may be a File, Blob, or MediaSource object

Usage as src or href

img.src = URL.createObjectURL(object);
a.href = URL.createObjectURL(object);

revokeObjectURL

Because createObjectURL creates at each invocation a new object, you need to delete it with the URL.revokeObjectURL() method after usage.

img.onload = function() {
    URL.revokeObjectURL(this.src);
}
a.addEventListener('click', (e) => {
    setTimeout(() => URL.revokeObjectURL(e.target.href), 30 * 1000);
});

Powered by ComboStrap