Red John
Red John

Reputation: 582

Google Chrome - download attribute of anchor tags

I've an extension which saves some files to the downloads folder. The code below is just for testing

//This lies in the background page of my extension
function fileTest(name) {
    var a = document.createElement('a');
    a.href = 'data:text/plain;base64,SGVsbG8gV29ybGQh'; //Hello World!
    a.download = name + '.txt';
    a.onclick = function (e) {console.log('[TEST] ' + name);return true;};
    a.click();
}
window.onload = function() {
    fileTest('test1');
    fileTest('test12');
    fileTest('test123');
}

only the first file "test1.txt" is saved to the disk, although the output of the console shows that there was 3 clicks

[TEST] test1

[TEST] test12

[TEST] test123

Is this an intentional limitation by the browser ? or there's something wrong with the code ?

Upvotes: 2

Views: 1525

Answers (1)

apsillers
apsillers

Reputation: 115910

When I run your code in a regular browsing session, I get a slide out notification (at the top of the window) that says

This site is attempting to download multiple files. Do you want to allow this?

So, yes, it is a security limitation of the browser to restrict downloads that are not user-initiated. You probably don't see the notification because the action is being performed by your background page.

The limitation seems to be one download per user action as demonstrated in this variant of your code:

window.onclick = function() {
    fileTest('test1');
}

This will allow unlimited downloads, but only one download per click event.

Upvotes: 3

Related Questions