Open In App

How to detect when browser receives download in web extension ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to detect download events in your browser. The browser supports something called extension API which allows you to do more than manipulate a web page. There are many APIs that can be used to make browser extensions and one among them is the downloads API. It enables us to interact with the browser’s download manager. You can use this API module to download files, cancel, pause, resume downloads, and show downloaded files in the file manager.

To use this API you need to have the “downloads” API permission specified in your manifest.json file. This file is basically used to build progressive web apps that manifest your web app. downloads API is accessed through browser API.

Example: The downloads API can only be accessed in the background context and so you need to add a field background in the below-mentioned manifest file. A background field is an object with a script field where you run your background js file.

{
   "name":"name of the extension",
   "version":"version",
   "permissions":["downloads", "downloads.open"],
   "manifest_version": 2,
   "background":{
         "scripts":["index.js"]
     },
}

Download API consists of three different events, which are described below:

  • downloads.onCreated: Fires when the download begins.
  • downloads.onErased: Fires when the download is erased from history.
  • downloads.onChanged: Fires with the download Id and an object containing the properties that change.

We can use any of the above events to detect the download event. Now, let us understand with a simple example of how to detect the download event

Here is the following code we are using to print the info about the downloaded item:

function handleCreated(downloadItem) {
    console.log(downloadItem);
}
browser.downloads.onCreated.addListener(handleCreated);

The onCreated event returns a downloadItem object that represents the downloaded file.

Here, the following code we are using to print the downloadedItem once it completes:

function handleChanged(DownloadDelta) {
    if (DownloadDelta.state && 
        DownloadDelta.state.current === "complete") {
           console.log(delta.id);
     }
}
browser.downloads.onChanged.addListener(handleChanged);

DownloadItem: This represents the downloaded file and is passed as an argument to the onCreated event.

There are various properties that are provided by the DownloadItem, which are described below:

  • bytesReceived: Number of bytes received so far from the host during the download
  • canResume: A boolean value indicating whether a currently paused download can be resumed from the point where it was paused
  • danger: A string indicating whether this download is thought to be safe or known to be suspicious.
  • endTime: A string representing the number of milliseconds between the UNIX epoch and when this download ended. This is undefined if the download has not yet finished.
  • error: A string indicating why a download was interrupted.
  • filename: A string representing the file’s absolute local path.
  • fileSize: A number indicating the total number of bytes in the whole file, after decompression. A value of -1 here means that the total file size is unknown.
  • id: An integer representing a unique identifier for the downloaded file that is persistent across browser sessions.
  • startTime: A string representing the number of milliseconds between the UNIX epoch and when this download began.
  • state: A string Indicating whether the download is progressing, interrupted, or complete.
  • totalBytes: A number indicating the total number of bytes in the file being downloaded. A value of -1 here means that the total number of bytes is unknown.
  • url: A string representing the absolute URL from which the file was downloaded.

Example 1: In this example, we will detect the download and print the downloadItem

Approach:

  • Create the manifest, HTML, and JS files and load the extension by following this article.
  • Open the background inspect console.
  • Run the HTML file at localhost:5501 (You can use VS code for this).
  • In the base.html file when you click the download link the background script prints the downloadItem.

manifest.json:

{
   "name":"my-extension",
   "version":"1.0.4",
   "description":"This Extension helps you detect download",
   "manifest_version": 2,
   "permissions":["downloads"],
     "background": 
       {
         "scripts": ["app.js"]
       }     
}

base.html:

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Download</title>
</head>
 
<body>
    <h1 style="color:green">GeekForGeeks</h1>
    <h3>
        How to detect when browser
        receives download in web extension ?
    </h3>
    <a href="http://127.0.0.1:5501/base.html" download>
      Download
      </a>
</body>
 
</html>


app.js:

Javascript




// App.js
function handleCreated(downloadItem) {
   console.log(downloadItem);
}
browser.downloads.onCreated.addListener(handleCreated);


Output: Here, I am running the base.html using a live server at URL http://127.0.0.1/base.html and the download href that is downloaded is also at the same origin.

 

The downloadItem object consoled by the background script in the above output is:

Object { 
    id: 7,
    url: "http://127.0.0.1:5501/base.html", 
    referrer: "http://127.0.0.1:5501/base.html", 
    filename: "C:\\Users\\NIKHIL\\Downloads\\base.html", 
    incognito: false, cookieStoreId: "firefox-default", 
    danger: "safe", 
    mime: "text/html", 
    startTime: "2022-10-06T08:10:17.599Z", 
    endTime: null, ...
}

Example 2: In this example, we will print the download URL with startTime on the console.

Approach: 

  • Create the manifest, HTML, and JS files and load the extension by following this article.
  • Open the background inspect console.
  • Run the HTML file at localhost:5501 (You can use VS code for this).
  • In the base.html file when you click the download link the background script prints the download URL.

manifest.json:

{
      "name":"my-extension",
      "version":"1.0.4",
      "description":"This Extension helps you detect download",
      "manifest_version": 2,
      "permissions":["downloads"],
    "background": {
        "scripts": ["app.js"]
    }     
}

base.html:

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Download</title>
</head>
 
<body>
    <h1 style="color:green">GeekForGeeks</h1>
    <h3>
        How to detect when browser receives
        download in web extension ?
    </h3>
    <a href="http://127.0.0.1:5501/base.html" download>
        Download
    </a>
</body>
 
</html>


app.js:

Javascript




function handleCreated(downloadItem) {
   console.log(
   `Download from ${downloadItem.url} +''
   +at starttime ${downloadItem.startTime}`);
}
browser.downloads.onCreated.addListener(handleCreated);


Output:

 



Last Updated : 09 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads