How to detect when browser receives download in web extension ?
Last Updated :
01 Aug, 2024
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:
Similar Reads
How to send PDF in express route response and force browser download ?
In this article, we will see how to send PDF files in the express route's response and make the browser force download the file. Approach: Load required packages, then create an express app.Define the routes for homepage and PDF download requests.Create an index.html file with a single button to dow
4 min read
How to download files from an external server with code in PHP ?
PHP provides many inbuilt variables or functions to perform this kind of operation. One of them is file_get_contents to download the files from the external server using PHP. file_get_contents() Function Parameters: $path: It declares the path of the file which we are going to fetch.$include_path: T
2 min read
How to detect the version of a browser ?
This article includes the basic theory and technique of browser detection in JavaScript-enabled web browsers. Description: Even though most of the scripts work on JavaScript-enabled web browser, there are certain things that is not going to work on some browsers i.e. they are browser dependent and i
4 min read
How to create a PHP detection browser script ?
A browser script is used to find the complete information of the web browser. A web browser is working on the hypertext transfer protocol and retrieves all the information on the internet and displays it on your desktop so that you can access all the things from anywhere. In this article, we will sh
2 min read
How to Setup Browsersync for Web Development in Ubuntu?
BrowserSync is an automation tool which is used extensively in web development. This tool makes our testing and tweaking faster by synchronizing file changes and interactions across many devices. Features of BrowserSync. Live reloading Interaction synchronization Simulate slower connections URL hist
2 min read
How to Intercept HTTP requests in web extension ?
In this article, we will understand to intercept the HTTP requests made by the browser using web extension API. What is Intercepting HTTP Request? Intercepting HTTP Requests means manipulating the HTTP requests made by the browser through the user or through asynchronous event handlers. With the hel
3 min read
How to detect browser or tab closing in JavaScript ?
Detecting browser or tab closure in JavaScript is essential for preventing data loss or unintended navigation. Using the beforeunload event, developers can prompt users with a confirmation dialog, ensuring they don't accidentally leave a page with unsaved changes or important information. The before
2 min read
How to check the current runtime environment is a browser in JavaScript ?
In this article, we will see how to detect the runtime environment in which our JavaScript code is running. Suppose you are building an application in Node.js and need to include that code in a webpage that would be run on a browser. This would cause some functions of a Node application not to work
2 min read
How to Detect Browser Language in PHP?
We can detect requesting browser's language using PHP's super global variable $_SERVER. It is a superglobal variable that holds information about headers, paths, and script locations. It is basically an associative array in PHP which has keys like SERVER_NAME, SERVER_ADDR, REQUEST_METHOD, etc. We ca
2 min read
How to handle file downloads in Express JS ?
When using ExpressJS, handling file uploads involves receiving files from clients. On the other hand, file downloads refer to serving files to clients. For file uploads, we typically use libraries to handle the file processing. On the other hand, for file downloads, it is common to use NodeJS's buil
2 min read