小编tob*_*y88的帖子

JavaScript click()方法仅在Chrome扩展程序中运行一次

我正在尝试在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
}
Run Code Online (Sandbox Code Playgroud)

这里是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 = …
Run Code Online (Sandbox Code Playgroud)

javascript jquery google-chrome google-chrome-extension content-security-policy

7
推荐指数
2
解决办法
2675
查看次数