0

我正在编写一个扩展程序来从站点下载图像,将其重命名并将其保存在“下载”下的新文件夹中。我已经成功了,但是我从其他站点下载的其他文件也被重命名为“undefined.ext”。

我想用 downloadItem.referrer 做一个 if else 但我正在下载的网站返回一个空字符串。

这就是我的 background.js 文件的样子。

    ...

    const downloadImg = (url, sequence) => {
      chrome.downloads.download({url: url}, function(downloadId) {
        nameMap[downloadId] = sequence;
      });
    }

    const downloadAllImages = (urls) => {
      for (key in urls) {
        downloadImg(urls[key], key);
      }
    }

    chrome.downloads.onDeterminingFilename.addListener(function(downloadItem, suggest) {
      id = downloadItem.id.toString();

referrer 是空字符串,所以我不能在这里做 if else 。

      console.log('downloadItem.referrer', downloadItem.url, id, downloadItem.state, downloadItem.referrer, downloadItem);
      let newName = `./${someNewFolder}/` + nameMap[id] + downloadItem.filename.slice(downloadItem.filename.lastIndexOf('.'));
      suggest({filename: newName, conflictAction: "overwrite" });
    });


    const handleOnClick = () => {
      chrome.tabs.query({
        url: "*://*.someUrlMatch.xyz/*/*",
        active: true, 
        currentWindow: true
      }, (tabs) => {
        if (tabs.length > 0) {
          downloadAllImages(urls);
        }
      });
    }

    chrome.browserAction.onClicked.addListener(function(tab) {
      handleOnClick();
    });

清单.json

    {
      "background": {
        "scripts": [ "js/jquery-3.3.1.slim.min.js", "js/background.js" ]
      },
      "browser_action": {
        "default_icon": "icon.png",
        "default_title": "Some Title",
      },
      "content_scripts": [
        {
          "matches": ["https://someUrlMatch.xyz/*/*"],
          "js": ["js/jquery-3.3.1.slim.min.js", "js/content.js"],
          "run_at": "document_end"
        }
      ],
      "description": "Some description",
      "manifest_version": 2,
      "name": "someName",
      "permissions": ["activeTab", "downloads", "tabs", "*://*.someUrlMatch.xyz/*/*" ],
      "version": "0.0"
    }
4

1 回答 1

1

蟋蟀。 谢谢你们的回答。所以我通过检查下载项目的绝对网址做了非最佳方式。

chrome.downloads.onDeterminingFilename.addListener((downloadItem, suggest) => {
  if (downloadItem.url === urlIWannaDownload) {
   ...
   suggest({filename: newName, conflictAction: "overwrite" });
  }
});
于 2018-03-06T01:08:55.533 回答