4

How can I use chrome.downloads.onDeterminingFilename to change downloaded file names if the files have extension of JPG or PNG?

I am looking at the example here:

chrome.downloads.onDeterminingFilename.addListener(function(item, __suggest) {
  function suggest(filename, conflictAction) {
    __suggest({filename: filename,
               conflictAction: conflictAction,
               conflict_action: conflictAction});
  }
  var rules = localStorage.rules;
  try {
    rules = JSON.parse(rules);
  } catch (e) {
    localStorage.rules = JSON.stringify([]);
  }
  for (var index = 0; index < rules.length; ++index) {
    var rule = rules[index];
    if (rule.enabled && matches(rule, item)) {
      if (rule.action == 'overwrite') {
        suggest(item.filename, 'overwrite');
      } else if (rule.action == 'prompt') {
        suggest(item.filename, 'prompt');
      } else if (rule.action == 'js') {
        eval(rule.action_js);
      }
      break;
    }
  }
});

This is confusing. How does chrome.downloads.onDeterminingFilename from above detect the name of the file? And once it detects, how did it change the file? Can anyone break down what these codes mean above?

Ref: http://developer.chrome.com/extensions/samples

P̲̳x͓L̳
  • 3,615
  • 3
  • 29
  • 37
Aero Wang
  • 8,382
  • 14
  • 63
  • 99

1 Answers1

2
  • As soon as the filename is determined onDeterminingFilename event is triggered upon which a callback function is called and it takes 2 parameters

    1. item object which contains data such as download id, url, filename, referrer etc. (see https://developer.chrome.com/extensions/downloads#type-DownloadItem)
    2. __suggest which must be called to pass suggestion either synchronously or asynchronously.
  • A suggest function is defined which will be used to call __suggest based on the specific rule
  • All the rules are accessed from the local memory and a for loop runs to iterate across them.
  • For each iteration based on the action data in the rule the suggest function is called with specific filename and conflictAction.

Basically the filename is aceessed using item.filename and a new filename is suggested by calling __suggest where the value for the key filename contains the new filename.

Namit Juneja
  • 498
  • 5
  • 13