chrome.downloads

This API is experimental. It is only available to Chrome users on the dev channel.

The downloads API allows you to programmatically initiate, monitor, manipulate, and search for downloads.

Manifest

You must declare the 'downloads' permission in the extension manifest to use this API, along with host permissions for any hosts that you may pass to download.

{
  'name': 'My extension',
  ...
  'permissions': [
    'downloads',
    '*://*.google.com'
  ],
  ...
}

If the URL's hostname is not specified in the permissions, then download will call its callback with a null downloadId and set the runtime.lastError object to indicate that the extension does not have permission to access that hostname.

Examples

You can find simple examples of using the downloads module in the examples/api/downloads directory. For other examples and for help in viewing the source code, see Samples.

chrome.downloads reference

Types

DangerType

file
The download's filename is suspicious.
url
The download's URL is known to be malicious.
content
The downloaded file is known to be malicious.
uncommon
The download's URL is not commonly downloaded and could be dangerous.
host
The download came from a host known to distribute malicious binaries and is likely dangerous.
safe
The download presents no known danger to the user's computer.
These string constants will never change, however the set of DangerTypes may change.

State

in_progress
The download is currently receiving data from the server.
interrupted
An error broke the connection with the file host.
complete
The download completed successfully.
These string constants will never change, however the set of States may change.

DownloadItem

Properties of DownloadItem

id ( integer )
An identifier that is persistent across browser sessions.
url ( string )
Absolute URL.
filename ( string )
Absolute local path.
incognito ( boolean )
False if this download is recorded in the history, true if it is not recorded.
danger ( DangerType )
Indication of whether this download is thought to be safe or known to be suspicious.
dangerAccepted ( optional boolean )
True if the user has accepted the download's danger.
mime ( string )
The file's MIME type.
startTime ( string )
The time when the download began in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){console.log(new Date(item.startTime))})})
endTime ( optional string )
The time when the download ended in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){if (item.endTime) console.log(new Date(item.endTime))})})
state ( State )
Indicates whether the download is progressing, interrupted, or complete.
paused ( boolean )
True if the download has stopped reading data from the host, but kept the connection open.
error ( optional integer )
Number indicating why a download was interrupted.
bytesReceived ( integer )
Number of bytes received so far from the host, without considering file compression.
totalBytes ( integer )
Number of bytes in the whole file, without considering file compression, or -1 if unknown.
fileSize ( integer )
Number of bytes in the whole file post-decompression, or -1 if unknown.
exists ( boolean )
Whether the downloaded file still exists. This information may be out of date because Chrome does not automatically watch for file removal. Call search() in order to trigger the check for file existence. When the existence check completes, if the file has been deleted, then an onChanged event will fire. Note that search() does not wait for the existence check to finish before returning, so results from search() may not accurately reflect the file system. Also, search() may be called as often as necessary, but will not check for file existence any more frequently than once every 10 seconds.

Methods

download

chrome.downloads.download(object options, function callback)

Download a URL. If the URL uses the HTTP[S] protocol, then the request will include all cookies currently set for its hostname. If both filename and saveAs are specified, then the Save As dialog will be displayed, pre-populated with the specified filename. If the download started successfully, callback will be called with the new DownloadItem's downloadId. If there was an error starting the download, then callback will be called with downloadId=undefined and runtime.lastError will contain a descriptive string. The error strings are not guaranteed to remain backwards compatible between releases. Extensions must not parse it.

Parameters

options ( object )
What to download and how.
url ( string )
The URL to download.
filename ( optional string )
A file path relative to the Downloads directory to contain the downloaded file. Cannot yet contain subdirectories; support for subdirectories will be implemented before this API is released to the stable channel. See onDeterminingFilename for how to dynamically suggest a filename after the file's MIME type and a tentative filename have been determined.
saveAs ( optional boolean )
Use a file-chooser to allow the user to select a filename.
method ( optional enumerated string ["GET", "POST"] )
The HTTP method to use if the URL uses the HTTP[S] protocol.
headers ( optional array of object )
Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a dictionary containing the keys name and either value or binaryValue, restricted to those allowed by XMLHttpRequest.
body ( optional string )
Post body.
callback ( optional function )
Called with the id of the new DownloadItem.

Callback

If you specify the callback parameter, it should specify a function that looks like this:

function(integer downloadId) {...};
downloadId ( integer )
chrome.downloads.search(object query, function callback)

Find DownloadItem. Set query to the empty object to get all DownloadItem. To get a specific DownloadItem, set only the id field.

Parameters

query ( object )
query ( optional string )
This space-separated string of search terms that may be grouped using quotation marks limits results to DownloadItem whose filename or url contain all of the search terms that do not begin with a dash '-' and none of the search terms that do begin with a dash.
startedBefore ( optional string )
Limits results to DownloadItem that started before the given ms since the epoch.
startedAfter ( optional string )
Limits results to DownloadItem that started after the given ms since the epoch.
endedBefore ( optional string )
Limits results to DownloadItem that ended before the given ms since the epoch.
endedAfter ( optional string )
Limits results to DownloadItem that ended after the given ms since the epoch.
totalBytesGreater ( optional integer )
Limits results to DownloadItem whose totalBytes is greater than the given integer.
totalBytesLess ( optional integer )
Limits results to DownloadItem whose totalBytes is less than the given integer.
filenameRegex ( optional string )
Limits results to DownloadItem whose filename matches the given regular expression.
urlRegex ( optional string )
Limits results to DownloadItem whose url matches the given regular expression.
limit ( optional integer )
Setting this integer limits the number of results. Otherwise, all matching DownloadItem will be returned.
orderBy ( optional string )
Setting this string to a DownloadItem property sorts the DownloadItem prior to applying the above filters. For example, setting orderBy='startTime' sorts the DownloadItem by their start time in ascending order. To specify descending order, prefix orderBy with a hyphen: '-startTime'.
id ( optional integer )
The id of the DownloadItem to query.
url ( optional string )
Absolute URL.
filename ( optional string )
Absolute local path.
danger ( optional DangerType )
Indication of whether this download is thought to be safe or known to be suspicious.
dangerAccepted ( optional boolean )
True if the user has accepted the download's danger.
mime ( optional string )
The file's MIME type.
startTime ( optional string )
The time when the download began in ISO 8601 format.
endTime ( optional string )
The time when the download ended in ISO 8601 format.
state ( optional State )
Indicates whether the download is progressing, interrupted, or complete.
paused ( optional boolean )
True if the download has stopped reading data from the host, but kept the connection open.
error ( optional integer )
Number indicating why a download was interrupted.
bytesReceived ( optional integer )
Number of bytes received so far from the host, without considering file compression.
totalBytes ( optional integer )
Number of bytes in the whole file, without considering file compression, or -1 if unknown.
fileSize ( optional integer )
Number of bytes in the whole file post-decompression, or -1 if unknown.
exists ( optional boolean )
Whether the downloaded file exists;
callback ( function )

Callback

The callback parameter should specify a function that looks like this:

function(array of DownloadItem results) {...};
results ( array of DownloadItem )

pause

chrome.downloads.pause(integer downloadId, function callback)

Pause the download. If the request was successful the download is in a paused state. Otherwise runtime.lastError contains an error message. The request will fail if the download is not active.

Parameters

downloadId ( integer )
The id of the download to pause.
callback ( optional function )
Called when the pause request is completed.

Callback

If you specify the callback parameter, it should specify a function that looks like this:

function() {...};

resume

chrome.downloads.resume(integer downloadId, function callback)

Resume a paused download. If the request was successful the download is in progress and unpaused. Otherwise runtime.lastError contains an error message. The request will fail if the download is not active.

Parameters

downloadId ( integer )
The id of the download to resume.
callback ( optional function )
Called when the resume request is completed.

Callback

If you specify the callback parameter, it should specify a function that looks like this:

function() {...};

cancel

chrome.downloads.cancel(integer downloadId, function callback)

Cancel a download. When callback is run, the download is cancelled, completed, interrupted or doesn't exist anymore.

Parameters

downloadId ( integer )
The id of the download to cancel.
callback ( optional function )
Called when the cancel request is completed.

Callback

If you specify the callback parameter, it should specify a function that looks like this:

function() {...};

getFileIcon

chrome.downloads.getFileIcon(integer downloadId, object options, function callback)

Retrieve an icon for the specified download. For new downloads, file icons are available after the onCreated event has been received. The image returned by this function while a download is in progress may be different from the image returned after the download is complete. Icon retrieval is done by querying the underlying operating system or toolkit depending on the platform. The icon that is returned will therefore depend on a number of factors including state of the download, platform, registered file types and visual theme. If a file icon cannot be determined, runtime.lastError will contain an error message.

Parameters

downloadId ( integer )
The identifier for the download.
options ( optional object )
size ( optional integer )
The size of the icon. The returned icon will be square with dimensions size * size pixels. The default size for the icon is 32x32 pixels.
callback ( function )
A URL to an image that represents the download.

Callback

The callback parameter should specify a function that looks like this:

function(string iconURL) {...};
iconURL ( optional string )

open

chrome.downloads.open(integer downloadId)

Open the downloaded file now if the DownloadItem is complete; returns an error through runtime.lastError otherwise. An onChanged event will fire when the item is opened for the first time.

Parameters

downloadId ( integer )
The identifier for the downloaded file.

show

chrome.downloads.show(integer downloadId)

Show the downloaded file in its folder in a file manager.

Parameters

downloadId ( integer )
The identifier for the downloaded file.

erase

chrome.downloads.erase(object query, function callback)

Erase matching DownloadItem from history. An onErased event will fire for each DownloadItem that matches query, then callback will be called.

Parameters

query ( object )
query ( optional string )
This space-separated string of search terms that may be grouped using quotation marks limits results to DownloadItem whose filename or url contain all of the search terms that do not begin with a dash '-' and none of the search terms that do begin with a dash.
startedBefore ( optional string )
Limits results to DownloadItem that started before the given ms since the epoch.
startedAfter ( optional string )
Limits results to DownloadItem that started after the given ms since the epoch.
endedBefore ( optional string )
Limits results to DownloadItem that ended before the given ms since the epoch.
endedAfter ( optional string )
Limits results to DownloadItem that ended after the given ms since the epoch.
totalBytesGreater ( optional integer )
Limits results to DownloadItem whose totalBytes is greater than the given integer.
totalBytesLess ( optional integer )
Limits results to DownloadItem whose totalBytes is less than the given integer.
filenameRegex ( optional string )
Limits results to DownloadItem whose filename matches the given regular expression.
urlRegex ( optional string )
Limits results to DownloadItem whose url matches the given regular expression.
limit ( optional integer )
Setting this integer limits the number of results. Otherwise, all matching DownloadItem will be returned.
orderBy ( optional string )
Setting this string to a DownloadItem property sorts the DownloadItem prior to applying the above filters. For example, setting orderBy='startTime' sorts the DownloadItem by their start time in ascending order. To specify descending order, prefix orderBy with a hyphen: '-startTime'.
id ( optional integer )
The id of the DownloadItem to query.
url ( optional string )
Absolute URL.
filename ( optional string )
Absolute local path.
danger ( optional DangerType )
Indication of whether this download is thought to be safe or known to be suspicious.
dangerAccepted ( optional boolean )
True if the user has accepted the download's danger.
mime ( optional string )
The file's MIME type.
startTime ( optional string )
The time when the download began in ISO 8601 format.
endTime ( optional string )
The time when the download ended in ISO 8601 format.
state ( optional State )
Indicates whether the download is progressing, interrupted, or complete.
paused ( optional boolean )
True if the download has stopped reading data from the host, but kept the connection open.
error ( optional integer )
Number indicating why a download was interrupted.
bytesReceived ( optional integer )
Number of bytes received so far from the host, without considering file compression.
totalBytes ( optional integer )
Number of bytes in the whole file, without considering file compression, or -1 if unknown.
fileSize ( optional integer )
Number of bytes in the whole file post-decompression, or -1 if unknown.
exists ( optional boolean )
Whether the downloaded file exists;
callback ( optional function )

Callback

If you specify the callback parameter, it should specify a function that looks like this:

function(array of integer erasedIds) {...};
erasedIds ( array of integer )

acceptDanger

chrome.downloads.acceptDanger(integer downloadId)

Prompt the user to accept a dangerous download. Does not automatically accept dangerous downloads. If the download is accepted, then an onChanged event will fire, otherwise nothing will happen. When all the data is fetched into a temporary file and either the download is not dangerous or the danger has been accepted, then the temporary file is renamed to the target filename, the |state| changes to 'complete', and onChanged fires.

Parameters

downloadId ( integer )
The identifier for the DownloadItem.

drag

chrome.downloads.drag(integer downloadId)

Initiate dragging the downloaded file to another application.

Parameters

downloadId ( integer )

Events

onCreated

chrome.downloads.onCreated.addListener(function(DownloadItem downloadItem) {...});

This event fires with the DownloadItem object when a download begins.

Listener Parameters

downloadItem ( DownloadItem )

onErased

chrome.downloads.onErased.addListener(function(integer downloadId) {...});

Fires with the downloadId when a download is erased from history.

Listener Parameters

downloadId ( integer )
The id of the DownloadItem that was erased.

onChanged

chrome.downloads.onChanged.addListener(function(object downloadDelta) {...});

When any of a DownloadItem's properties except bytesReceived changes, this event fires with the downloadId and an object containing the properties that changed.

Listener Parameters

downloadDelta ( object )
id ( integer )
The id of the DownloadItem that changed.
url ( optional object )
The change in url, if any.
previous ( optional string )
current ( optional string )
filename ( optional object )
The change in filename, if any.
previous ( optional string )
current ( optional string )
danger ( optional object )
The change in danger, if any.
previous ( optional string )
current ( optional string )
dangerAccepted ( optional object )
The change in dangerAccepted, if any.
previous ( optional boolean )
current ( optional boolean )
mime ( optional object )
The change in mime, if any.
previous ( optional string )
current ( optional string )
startTime ( optional object )
The change in startTime, if any.
previous ( optional string )
current ( optional string )
endTime ( optional object )
The change in endTime, if any.
previous ( optional string )
current ( optional string )
state ( optional object )
The change in state, if any.
previous ( optional string )
current ( optional string )
paused ( optional object )
The change in paused, if any.
previous ( optional boolean )
current ( optional boolean )
error ( optional object )
The change in error, if any.
previous ( optional integer )
current ( optional integer )
totalBytes ( optional object )
The change in totalBytes, if any.
previous ( optional integer )
current ( optional integer )
fileSize ( optional object )
The change in fileSize, if any.
previous ( optional integer )
current ( optional integer )
exists ( optional object )
The change in exists, if any.
previous ( optional boolean )
current ( optional boolean )

onDeterminingFilename

chrome.downloads.onDeterminingFilename.addListener(function(DownloadItem downloadItem, function suggest) {...});

During the filename determination process, extensions will be given the opportunity to override the target DownloadItem.filename. Each extension may not register more than one listener for this event. Each listener must call suggest exactly once, either synchronously or asynchronously. If the listener calls suggest asynchronously, then it must return true. If the listener neither calls suggest synchronously nor returns true, then suggest will be called automatically. The DownloadItem will not complete until all listeners have called suggest. Listeners may call suggest without any arguments in order to allow the download to use downloadItem.filename for its filename, or pass a FilenameSuggestion object to suggest in order to override the target filename. If more than one extension overrides the filename, then the last extension installed whose listener passes a FilenameSuggestion object to suggest wins. In order to avoid confusion regarding which extension will win, users should not install extensions that may conflict. If the download is initiated by download and the target filename is known before the MIME type and tentative filename have been determined, use DownloadOptions.filename instead.

Listener Parameters

downloadItem ( DownloadItem )
suggest ( function )

Callback

The suggest parameter should specify a function that looks like this:

function(object suggestion) {...};
suggestion ( optional object )
filename ( string )
The DownloadItem's new target DownloadItem.filename, as a path relative to the user's default Downloads directory, possibly containing subdirectories. Absolute paths, empty paths, and paths containing back-references ".." will be ignored.
overwrite ( optional boolean )
Whether to overwrite any existing files.

Sample Extensions that use chrome.downloads

  • Download Selected Links – Select links on a page and download them.
  • Downloads Overwrite Existing Files – All downloads overwrite existing files instead of adding ' (1)', ' (2)', etc.