Browser / Javascript - Object URL (createObjectURL / revokeObjectURL)
Table of Contents
About
The ObjectUrl is an object that represents the data URL strings.
Example
A download link with text data
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:
- Create the blob data container with plain text
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.
- For an image:
img.onload = function() {
URL.revokeObjectURL(this.src);
}
- For a anchor
a.addEventListener('click', (e) => {
setTimeout(() => URL.revokeObjectURL(e.target.href), 30 * 1000);
});