window
.
navigator
&&
window
.
navigator
.
msSaveOrOpenBlob
)
return
window
.
navigator
.
msSaveOrOpenBlob
(
blob
);
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const
data
=
window
.
URL
.
createObjectURL
(
blob
);
const
link
=
document
.
createElement
(
'
a
'
);
link
.
href
=
data
;
link
.
download
=
name
;
// this is necessary as link.click() does not work on the latest firefox
link
.
dispatchEvent
(
new
MouseEvent
(
'
click
'
,
{
bubbles
:
true
,
cancelable
:
true
,
view
:
window
setTimeout
(()
=>
{
// For Firefox it is necessary to delay revoking the ObjectURL
window
.
URL
.
revokeObjectURL
(
data
);
link
.
remove
();
},
100
);
// Usage
downloadBlob
(
blob
,
'
myfile.pdf
'
);
NOTICE
As Kaltu pointed out in the comments:
it seems "window.URL.createObjectURL()" had been blocked by all major browsers since 2019 for security reasons.
This approach should work as expected:
functiondownloadBlob(blob,name='file.txt'){// Convert your blob into a Blob URL (a special url that points to an object in the browser's memory)constblobUrl=URL.createObjectURL(blob);// Create a link elementconstlink=document.createElement("a");// Set link's href to point to the Blob URLlink.href=blobUrl;link.download=name;// Append link to the bodydocument.body.appendChild(link);// Dispatch click event on the link// This is necessary as link.click() does not work on the latest firefoxlink.dispatchEvent(newMouseEvent('click',{bubbles:true,cancelable:true,view:window// Remove link from bodydocument.body.removeChild(link);// UsageletjsonBlob=newBlob(['{"name": "test"}'])downloadBlob(jsonBlob,'myfile.json');
I tried this snippet and hit by this error: "Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided."
Upon a quick search it seems "window.URL.createObjectURL()" had been blocked by all major browsers since 2019 for security reasons.
Ohh, damn, thanks for the information. I did not know this, it worked when I tested it, maybe my browser was not up to date or something.
I will add a warning and research a compatible way of doing it :P
I don't think so, as it is a native download in another window/tab, like if you open a link to a file and chrome downloads it automatically.
I think you might be able to know when it is done, but have not played with that.
Do you mean downloading a file from a URL?
If that is the case, you first need to read the URL as a blob. I think you can do this with FileReader or with a simple fetch/ajax/http request. Then, once you have the Blob you can use my method above to download it.