downloads.download()

downloads API の download() 関数では URL とそのほかのオプションの設定を行うことでファイルのダウンロードをすることができます。

  • HTTP もしくは HTTPS のプロトコルを使用した URL を指定した場合、対象のホスト名に対応する全ての cookie を含んだリクエストが送られます。
  • filenamesaveAs が指定されている場合、指定された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 string representing 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 array of objects representing 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 keys name and either value or binaryValue, restricted to those allowed by XMLHttpRequest.

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 boolean that 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.useDownloadDir in about:config).

url

ダウンロードする URL をstringで指定します。

戻り値

Promiseが返却されます。ダウンロードが成功した場合、new downloads.DownloadItem (en-US)の id が格納された promise を受け取ります。対して、promise が reject された場合は、エラーメッセージを受け取ります。

ブラウザーの互換性

BCD tables only load in the browser

以下のダウンロードの例ではファイル名と保存場所を指定し、conflictActionuniquifyを指定しています。

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 を元にしています。