Skip to content

Instantly share code, notes, and snippets.

@rudiedirkx
Created May 6, 2012 16:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rudiedirkx/2623261 to your computer and use it in GitHub Desktop.
Save rudiedirkx/2623261 to your computer and use it in GitHub Desktop.
Download any File/Blob via JS
/**
* `url` can be a data URI like data: or a blob URI like blob: or an existing, public resource like http:
* `filename` is the (default) name the file will be downloaded as
*/
function download( url, filename ) {
var link = document.createElement('a');
link.setAttribute('href',url);
link.setAttribute('download',filename);
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
}
@douglasg14b
Copy link

This doesn't work for anything that has a lot of text, you will need to actually download it as a blob otherwise.

@joetIO
Copy link

joetIO commented May 25, 2017

	var event = document.createEvent('MouseEvents');

	event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);

	link.dispatchEvent(event);

You can write just!:

link.click()

@willwillems
Copy link

For the people working with Blobs, you probably need this:
const blobUrl = URL.createObjectURL(blob)

@polyrabbit
Copy link

@yousayed link.click() doesn't work for Firefox 52.5.3

@Alex2357
Copy link

doen't work for outube

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment