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

て烟熏妆下的殇ゞ 提交于 2019-12-22 11:05:17

问题


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


回答1:


  • 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.



来源:https://stackoverflow.com/questions/22736325/how-can-i-use-chrome-downloads-ondeterminingfilename-to-change-downloaded-file-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!