【发布时间】:2012-12-25 19:54:56
【问题描述】:
我正在尝试在 Chrome 扩展程序中下载多个文件。下面的代码创建一个文件的虚拟链接,然后触发下载文件的 .click() 事件。 问题是只有第一个 .click() 事件触发下载。随后的 .click() 事件将被忽略。
这里是 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"});
});
我试过了:
Chrome Extension write to file system 中描述的使用 FileSaver.js 下载文件的不同方法,结果完全相同,第一个文件被下载,第二个不是
如Is it possible to make two .click method calls in javascript 中所述添加超时,导致违反内容安全策略,我尝试使用Content-Security-Policy error in google chrome extension making 中描述的方法解决此问题,但没有成功
使用JQuery click event works only once 中描述的 jQuery .live 方法,也没有成功,但我不能 100% 确定我正确地实现了这个方法(如果人们认为这种方法应该解决它,可以稍后发布代码)
很惊讶为什么简单地保存多个文件如此困难。感谢任何帮助。
【问题讨论】:
-
等待几个月,
chrome.downloadsAPI 已广泛可用。关于 CSP 错误:a是一个链接,其toString属性返回链接的目标。因此,如果您使用setTimeout(a, 300);,它会尝试评估链接的目标。默认情况下禁止字符串即代码评估,因此您会收到错误消息。但是,如果您使用setTimeout(function() {a.click();}, 300);,文件仍然没有被下载。 -
你找到解决这个问题的临时方法了吗?
-
我认为这不可能是安全问题。如果可能的话,我几乎可以通过单击打开无限弹出/下载。
-
由于围绕这个问题的活动再次活跃起来,这就是我最终要做的事情:我遵循了 Rob W 的建议并正在使用 chrome.downloads.download(DownloadOptions options, function callback) 方法。它完美地工作。我的 Chrome 扩展程序仅供内部使用,因此使用它的每个人都使用 Chrome Canary (google.com/intl/en/chrome/browser/canary.html)。
-
我不是在处理扩展程序(只是将 sn-ps 粘贴到控制台中),但我使用
el.dispatchEvent(clickEvent)(参见 zertosh 的回答)结合setTimeout(function() { download_next() }, 500)使它工作。 500 毫秒是合理的;使用 100 毫秒或更短时间时,某些文件无法下载。
标签: javascript jquery google-chrome google-chrome-extension content-security-policy