1chrome.downloads.onDeterminingFilename.addListener(function(item, suggest) {
2 if (item.referrer.search("gutenberg.org") == -1) {
3 // If the file does not come from gutenberg.org, suggest nothing new.
4 suggest({filename: item.filename});
5 } else {
6 // Otherwise, fetch the book's title in storage...
7 chrome.storage.local.get([item.referrer], function(result) {
8 if (result[item.referrer] == null) {
9 // ...and if we find don't find it, suggest nothing new.
10 suggest({filename: item.filename});
11 console.log('Nothing done.');
12 }
13 else {
14 // ...if we find it, suggest it.
15 fileExt = item.filename.split('.').pop();
16 var newFilename = "gutenberg/" + result[item.referrer] + "." + fileExt;
17 suggest({filename: newFilename});
18 console.log('New filename: ' + newFilename);
19 }
20 });
21 // Storage API is asynchronous so we need to return true
22 return true;
23 }
24 });
25