问题
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 parametersitem
object which contains data such as download id, url, filename, referrer etc. (see https://developer.chrome.com/extensions/downloads#type-DownloadItem)- __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 therule
the suggest function is called with specificfilename
andconflictAction
.
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