I'm trying to download multiple files in a Chrome extension. The following code creates a dummy link to a file, then triggers the .click() event which downloads the file. The problem is that only the first .click() event triggers a download. Subsequent .click() events are ignored.
Here the manifest.json:
{
"name": "Simple File Downloader",
"version": "0.1",
"permissions": ["contextMenus", "http://*/"],
"background": {
"persistent": false,
"scripts": ["sample.js"]
},
"content_security_policy": "script-src 'self'; object-src 'self'",
"manifest_version": 2
}
Here the sample.js:
function onClickHandler(info, tab) {
var a = document.createElement('a');
a.href = 'http://or.cdn.sstatic.net/chat/so.mp3';
a.download = 'so.mp3';
document.body.appendChild(a);
a.click(); // this click triggers the download
// this timeout violates content security policy
// setTimeout(a, 300);
a.click(); // this click doesn't do anything
document.body.removeChild(a);
a = document.createElement('a');
a.href = 'http://or.cdn.sstatic.net/chat/so.mp3';
a.download = 'so.mp3';
document.body.appendChild(a);
a.click(); // this click doesn't do anything either
document.body.removeChild(a);
};
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({"title": "Download File", "id":"download_file"});
});
I've tried:
different approaches for downloading files as described in Chrome Extension write to file system using FileSaver.js, with the exact same result, first file is downloaded, second one is not
adding timeouts as described in Is it possible to make two .click method calls in javascript, resulting in content-security-policy violation, which I tried to work around using the approach described in Content-Security-Policy error in google chrome extension making, but without success
using the jQuery .live method as described in JQuery click event works only once, also without success, but I'm not 100% sure I implemented this one correctly (can post code later if people think this approach should solve it)
Surprised why it's so hard to simply save multiple files. Appreciate any help.