Downloads.jsm

The Downloads.jsm JavaScript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration. To use it, you first need to import the code module into your JavaScript scope:

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

Method overview

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

Constants

Constant Description
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.

Properties

Attribute Type Description
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.");
}

Methods

createDownload()

Creates a new Download object.

Promise<Download> createDownload(
  Object aProperties
);
Parameters
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

The newly created Download object.

fetch()

Downloads data from a remote network location to a local file.

This download method does not provide user interface or the ability to cancel or restart the download programmatically. For that, you should obtain a reference to a Download object using the createDownload() function.

Since the download cannot be restarted, any partially downloaded data will not be kept in case the download fails.

Promise fetch(
  aSource,
  aTarget,
  Object aOptions
);
Parameters
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.

Calling this function may cause the download list to be reloaded from the previous session, if it wasn't loaded already.

Promise<DownloadList> getList(aType);
Parameters
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);
Parameters
aType
This can be Downloads.PUBLIC, Downloads.PRIVATE, or Downloads.ALL.
Promise resolves to

The requested DownloadSummary object.

Examples

Downloading to a local file

This example downloads an HTML file without showing progress, handling errors programmatically.

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);

Observing downloads

This example logs a message every time a change occurs in one of the global download lists.

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

 

Document Tags and Contributors

 Contributors to this page: Sheppy, Yuan.Xulei, Laurentj, Nmaier, lindacrdr, P.A., trevorh
 Last updated by: Sheppy,