0

I'm writing an extension to download images from a site, rename it and save it in a new Folder under Downloads. I've been successful with this but other files that I download from other sites also get renamed to "undefined.ext".

I wanted to do an if else with downloadItem.referrer but the site that I'm downloading from returns an empty string.

This is what my background.js file looks like.

    ...

    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 is empty string so I can't do an if else here.

      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();
    });

manifest.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"
    }
Sam Sama
  • 21
  • 4

1 Answers1

2

crickets. Thanks for the answer guys. So I did the un-optimal way by checking for the absolute url of the download item.

chrome.downloads.onDeterminingFilename.addListener((downloadItem, suggest) => {
  if (downloadItem.url === urlIWannaDownload) {
   ...
   suggest({filename: newName, conflictAction: "overwrite" });
  }
});
Sam Sama
  • 21
  • 4