Browser / Javascript - Object URL (createObjectURL / revokeObjectURL)
About
An ObjectUrl is the representation of blob object as a data URL strings that can be used with any fetch HTML element that accepts an URL as an attribute.
Example
Raw HTML
Example: This HTML was generated with the code in the next example.
<a href="blob:https://datacadamia.com/35a824bb-3a18-42d0-81c9-24df9aa548b2">Hello-world.txt</a>
The id blob:https://datacadamia.com/4067f3b2-dba2-4bdc-8199-e86fd670aa67 is:
- temporary,
- generated
- and managed by the browser.
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);
});
Get blob object from ObjectURL
You can get a blob object by fetching the URL
let blob = await fetch(url).then(r => r.blob());