MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Downloads.jsm

この翻訳は不完全です。英語から この記事を翻訳 してください。

Downloads.jsmはダウンロードに関する機能を提供するJavaScriptモジュールです。新規にダウンロードを開始したり、ダウンロード中に制御を行ったり、ダウンロードに関連する設定を呼び出したりできます。これを使用するにはまずモジュールをインポートする必要があります。

Components.utils.import("resource://gre/modules/Downloads.jsm");

メソッドの概要

Promise<Download> createDownload(Object aProperties);
Promise<void> fetch(aSource, aTarget, [optional] Object aOptions);
Promise<DownloadList> getList(aType);
Promise<DownloadSummary> getSummary(aType);

定数

定数 説明
PUBLIC Work on downloads that were not started from a private browsing window.
PRIVATE Work on downloads that were started from a private browsing window.
ALL Work on both Downloads.PRIVATE and Downloads.PUBLIC downloads.

プロパティ

属性 説明
Error Read only Constructor Constructor for a DownloadError object. When you catch an exception during a download, you can use this to verify if ex instanceof Downloads.Error, before reading the exception properties with the error details. Example (using Task.jsm):
try {
  yield Downloads.fetch(sourceUri, targetFile);
} catch (ex if ex instanceof Downloads.Error && ex.becauseTargetFailed) {
  console.log("Unable to write to the target file, ignoring the error.");
}

メソッド

createDownload()

新しくDownloadオブジェクトを生成します。

Promise<Download> createDownload(
  Object aProperties
);
パラメーター
aProperties
Provides the initial properties for the newly created download. This matches the serializable representation of a Download object. Some of the most common properties in this object include:
  • source: String containing the URI for the download source. Alternatively, may be an nsIURI, a DownloadSource object, or an object with the following properties:
    • url: String containing the URI for the download source.
    • isPrivate: Optional Indicates whether the download originated from a private window. If omitted, the download is public.
    • referrer: Optional String containing the referrer URI of the download source. Can be omitted or null if no referrer should be sent or the download source is not HTTP.
  • target: String containing the path of the target file. Alternatively, may be an nsIFile, a DownloadTarget object, or an object with the following properties:
    • path: String containing the path of the target file.
  • saver: Optional String representing the class of the download operation. If omitted, defaults to "copy". Alternatively, may be the serializable representation of a DownloadSaver object.
Promise resolves to

新しく生成されたDownloadオブジェクト.

fetch()

ネットワーク上のデータをローカルにダウンロードします。

この関数はダウンロードをキャンセルしたり再開するインターフェイスを提供していません。その場合はcreateDownload()関数を利用してDownloadオブジェクトを参照してください。

ダウンロードは再開されないため、たとえダウンロードが失敗しても部分的にダウンロードデータが保存されることはありません。

Promise fetch(
  aSource,
  aTarget,
  Object aOptions
);
パラメーター
aSource
String containing the URI for the download source. Alternatively, may be an nsIURI or a DownloadSource object.
aTarget
String containing the path of the target file. Alternatively, may be an nsIFile or a DownloadTarget object.
aOptions Optional
An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields:
  • isPrivate: Optional Indicates whether the download originated from a private window. If omitted, the download is public.
Promise resolves to

undefined when the download has finished successfully and you can access the target file.

Promise can be rejected with

DownloadError if the download failed.

getList()

Retrieves the specified type of DownloadList object. There is one download list for each type, and this method always retrieves a reference to the same download list when called with the same argument.

この関数を呼び出すと、ダウンロードリストが(すでにロードされている場合をのぞいて)リロードされます。

Promise<DownloadList> getList(aType);
パラメーター
aType
This can be Downloads.PUBLIC, Downloads.PRIVATE, or Downloads.ALL. Downloads added to the Downloads.PUBLIC and Downloads.PRIVATE lists are reflected in the Downloads.ALL list, and downloads added to the Downloads.ALL list are also added to either the Downloads.PUBLIC or the Downloads.PRIVATE list based on their properties.
Promise resolves to

The requested DownloadList object.

getSummary()

Retrieves the specified type of DownloadSummary object. There is one download summary for each type, and this method always retrieves a reference to the same download summary when called with the same argument.

Calling this function does not cause the list of public downloads to be reloaded from the previous session. The summary will behave as if no downloads are present until the getList() method is called.

Promise<DownloadSummary> getSummary(aType);
パラメーター
aType
This can be Downloads.PUBLIC, Downloads.PRIVATE, or Downloads.ALL.
Promise resolves to

The requested DownloadSummary object.

ローカルにダウンロードする

この例では、HTMLファイルをダウンロードしています。ダウンロードの進捗状況を表示したり、エラー処理は行っていません。

Components.utils.import("resource://gre/modules/Downloads.jsm");
Components.utils.import("resource://gre/modules/osfile.jsm")
Components.utils.import("resource://gre/modules/Task.jsm");

Task.spawn(function () {

  yield Downloads.fetch("http://www.mozilla.org/",
                        OS.Path.join(OS.Constants.Path.tmpDir,
                                     "example-download.html"));

  console.log("example-download.html has been downloaded.");

}).then(null, Components.utils.reportError);

ダウンロードの監視

この例では、グローバルなダウンロードリストに変化が発生するたびに、メッセージを記録しています。

To demonstrate the logging, a new download is started while a message box is being shown. The download is stopped and removed from the list when the message box is closed, regardless of whether it has been completed or not.

Components.utils.import("resource://gre/modules/Downloads.jsm");
Components.utils.import("resource://gre/modules/osfile.jsm")
Components.utils.import("resource://gre/modules/Task.jsm");

Task.spawn(function () {

  let list = yield Downloads.getList(Downloads.ALL);

  let view = {
    onDownloadAdded: download => console.log("Added", download),
    onDownloadChanged: download => console.log("Changed", download),
    onDownloadRemoved: download => console.log("Removed", download)
  };

  yield list.addView(view);
  try {
    let download = yield Downloads.createDownload({
      source: "http://www.mozilla.org/",
      target: OS.Path.join(OS.Constants.Path.tmpDir, "example-download.html"),
    });
    list.add(download);
    try {
      download.start();
      alert("Now monitoring all downloads. Close the message to stop.");
    } finally {
      yield list.remove(download);
      yield download.finalize(true);
    }
  } finally {
    yield list.removeView(view);
  }

}).then(null, Components.utils.reportError);

Conversion from nsIDownloadManager

Starting in Firefox for Desktop version 26, the nsIDownloadManager and nsIDownload interfaces are not available anymore.

The new module works differently from the old component. In general, you should be aware of the following highlights:

  • There is no difference between active downloads and finished downloads. The Download object can be used without requiring direct database access.
  • Observer notifications (for example, "dl-done") and download listeners are replaced by views on the DownloadList object returned by the getList() method.
  • Object identity replaces the use of numeric identifiers. You can use Download objects as keys in a Set or Map to associate your own state to them for the session.
  • There is no separate count of active downloads. If a count is needed, it should be maintained using a view on a DownloadList.
  • The start() method can be used to restart a failed download. Handling of downloads that have been paused is also different.

While some of the legacy methods and properties have an equivalent in Downloads.jsm, there might be subtle differences in behavior. For example, the properties that handle progress are now more detailed and don't use the special value -1 anymore. You may see the documentation of the new methods and properties for details.

Using it in a XUL app

In a XUL standalone application (running with XULRunner or firefox --app), you have to do additionnal things in order to use the new download manager. By default it is not enabled. It will be enabled when the bug 851471 will be closed. If you don't activate it, you could use Downloads.jsm, but your view will not be called by the external helper app service (when a user click on a file to download, in a web page). To enable the new download manager :

 Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar)
                   .registerFactory(Components.ID("{1b4c85df-cbdd-4bb6-b04e-613caece083c}"), "", "@mozilla.org/transfer;1", null);

 

See also

 

ドキュメントのタグと貢献者

 このページの貢献者: takaron
 最終更新者: takaron,