我试图在Chrome扩展中下载多个文件。以下代码创建一个到文件的虚拟链接,然后触发下载该文件的.click()事件。 问题是只有第一个.click()事件触发下载。后续的.click()事件被忽略。JavaScript click()方法只能在Chrome扩展中运行一次
这里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
}
这里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"});
});
我已经试过:
不同的方法下载文件描述使用FileSaver.js,具有完全相同的结果Chrome Extension write to file system d,第一个文件被下载,二是不
增加超时在Is it possible to make two .click method calls in javascript描述,导致内容安全策略违规,我试图解决使用Content-Security-Policy error in google chrome extension making描述的方法,但都没有成功
使用jQuery .live方法在JQuery click event works only once描述,也没有成功,但我不是100%肯定我正确地实现这一个(可以在以后发布的代码,如果人认为这种方法应该可以解决它)
惊讶为什么很难简单地保存多个文件。感谢任何帮助。
等了几个月,和['chrome.downloads'](https://developer.chrome.com/dev/extensions/downloads。HTML)API广泛可用。关于CSP错误:'a'是一个链接,其'toString'属性返回链接的目标。所以,如果你使用'setTimeout(a,300);',它会尝试评估链接的目标。字符串作为代码评估是默认禁止的,所以你会得到错误。但是,如果使用'setTimeout(function(){a.click();},300);',该文件仍然没有被下载。 –
您是否找到解决此问题的临时解决方案? – coneybeare
我认为这是不可能的安全问题。如果可能的话,那么事实上我可以打开无限弹出/下载只需点击一下。 –