WebExtensionsを使用してこれを行う「適切な」方法は、Firefoxでサポートされていません(まだですか?)。 Google Chromeには'onDeterminingFilename'イベントがあり、ユーザーにファイル名を「示唆」させることができます。この場合、必要に応じてユーザーがあなたの内線番号を無効にすることを可能にする「提案」が良いかもしれません。
これを行うブルートフォースの方法は、リスナーをdownloads.onCreated
に追加することです。そのリスナーにはdownloads.DownloadItem
が渡され、url
とfilename
の両方が得られます。リスナーはdownloads.cancel()
をダウンロードして、新しいものをdownloads.download()
のfilename
で開始できます。
実際にはどのように動作するかは、ユーザーとのやりとりに関して実際にいつdownloads.onCreated
イベントが発生するかによって異なります。ユーザーの「名前を付けて保存」ダイアログの前または後に起動しますか?あなたは、ユーザーが持っていると思う気持ちに最も適しているかを調べるために、これをテストする必要があります。 downloads.State
タイプに含めることができる制限された値のセットは、「名前を付けて保存」ダイアログが完了した後にのみイベントが発生することを示しますが、それは正確な指示ではない可能性があります。 「名前を付けて保存」ダイアログの前に起動した場合は、アドオンが提案しているファイル名でこのダイアログを表示させることができます。downloads.download()
次のようなものがあります。
var ignoreDownloadUrls=[];
var ignoreDownloadIds=[];
chrome.downloads.onCreated.addlistener(forceDownloadFilenameIfUrlMatch);
function forceDownloadFilenameIfUrlMatch(downloadItem){
//Check the URL for duplication (may not be needed, need to test).
let foundUrlIndex = ignoreDownloadUrls.findIndex(function(element,index){
if(element === downloadItem.url){
return true;
}//else
return false;
});
if(foundUrlIndex>-1) {
//This is the callback resulting from our creating the download
// with the new filename. We only want to ignore the URL once,
// so, remove the URL from our ignore list.
// This makes the assumption that the events we get are reasonably
// orderly (only one created event per URL which we want to
// change, etc.). This may need to be more complex in real use.
ignoreDownloadUrls.splice(foundUrlIndex,1);
//We do not want to change this download, as we created it.
return;
}
//Test the ID for one we created:
let foundIdIndex = ignoreDownloadIds.findIndex(function(element,index){
if(element === downloadItem.id){
return true;
}//else
return false;
});
if(foundIdIndex>-1) {
//This is an event resulting from our creating the download
// with the new filename.
//We do not want to change this download, as we created it.
return;
}
if(downloadItem.url.idexOf(myMatchString) >-1){
chrome.downloads.cancel(downloadItem.id);
//Remember the URL so we don't change it twice.
// Remembering the URL may not be the best way to do this. Need
// to test as to the order which events and the download callback
// occur.
ignoreDownloadUrls.push(download.url);
chrome.downloads.download({
url: downloadItem.url,
filename: myNewFilename
}, function(id){
//We could use the callback of the downloads.download() to remember
// the downloadId of the download we created and only ignore that
// one. That would rely on the callback being called prior to the
// new onCreated event. Might work that way in practice. It
// would certainly be better to remember the specifically created
// downloadId rather than just ignore (once) a specific URL.
// Testing should indicate if we need to use the download ID,
// or ignore the URL (once).
//Remember the downloadId so we don't change it twice.
ignoreDownloadIds.push(id);
});
}
}