downloads.download()
downloads API の download() 関数では URL とそのほかのオプションの設定を行うことでファイルのダウンロードをすることができます。
- HTTP もしくは HTTPS のプロトコルを使用した URL を指定した場合、対象のホスト名に対応する全ての cookie を含んだリクエストが送られます。
filenameとsaveAsが指定されている場合、指定されたfilenameが設定された[名前をつけて保存]のダイアログが開きます。
この関数は非同期に実行され、Promiseを返します。
構文
js
var downloading = browser.downloads.download(
options // object
)
パラメータ
options-
この
objectではダウンロードしたいファイルやその他のダウンロードに関する設定を指定します。指定できるプロパティは以下です。body省略可-
リクエストの body を
stringで指定します。 conflictAction省略可-
A string representing the action you want taken if there is a filename conflict, as defined in the
downloads.FilenameConflictAction(en-US) type (defaults to "uniquify" when it is not specified). filename省略可-
A
stringrepresenting a file path relative to the default downloads directory — this provides the location where you want the file to be saved, and what filename you want to use. Absolute paths, empty paths, and paths containing back-references (../) will cause an error. If omitted, this value will default to the filename already given to the download file, and a location immediately inside the downloads directory. headers省略可-
An
arrayofobjectsrepresenting extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a dictionary object containing the keysnameand eithervalueorbinaryValue, restricted to those allowed byXMLHttpRequest. incognito省略可-
A
boolean: if present and set to true, then associate this download with a private browsing session. This means that it will only appear in the download manager for any private windows that are currently open. method省略可-
HTTP[S]を使用した URL を指定した際、HTTP メソッドを
stringで指定します。GET もしくは POST を設定できます。 saveAs省略可-
A
booleanthat specifies whether to provide a file chooser dialog to allow the user to select a filename (true), or not (false).If this option is omitted, the browser will show the file chooser or not based on the general user preference for this behavior (in Firefox this preference is labeled "Always ask you where to save files" in about:preferences, or
browser.download.useDownloadDirin about:config). url-
ダウンロードする URL を
stringで指定します。
戻り値
Promiseが返却されます。ダウンロードが成功した場合、new downloads.DownloadItem (en-US)の id が格納された promise を受け取ります。対して、promise が reject された場合は、エラーメッセージを受け取ります。
ブラウザーの互換性
BCD tables only load in the browser
例
以下のダウンロードの例ではファイル名と保存場所を指定し、conflictActionにuniquifyを指定しています。
js
function onStartedDownload(id) {
console.log(`Started downloading: ${id}`);
}
function onFailed(error) {
console.log(`Download failed: ${error}`);
}
var downloadUrl = "https://example.org/image.png";
var downloading = browser.downloads.download({
url : downloadUrl,
filename : 'my-image-again.png',
conflictAction : 'uniquify'
});
downloading.then(onStartedDownload, onFailed);
メモ: この API は Chromium の chrome.downloads API を元にしています。