How do I handle download prompts in Puppeteer?
Rashid D
rashid d profile pic

Handling download prompts in Puppeteer involves modifying the browser's default download behavior using thepage._client.send() method. Here's a detailed explanation of how to handle download prompts in Puppeteer: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Modifying the browser's default download behavior: By using thepage._client.send() method, you can modify the browser's default download behavior and handle download prompts.

1
2
3
4
5
6

   await page._client.send('Page.setDownloadBehavior', {
     behavior: 'allow',
     downloadPath: '/path/to/save/downloads',
   });
   

In this example,page._client.send() is called with the'Page.setDownloadBehavior' method to modify the download behavior. Thebehavior property is set to'allow' to allow downloads, and thedownloadPath property is set to the desired path where the downloaded files should be saved. Replace'/path/to/save/downloads' with the actual path on your system. 3. Triggering a download and handling the file: Once the download behavior has been modified, you can trigger a download by interacting with the relevant element or initiating a download programmatically. After the file is downloaded, you can handle it as needed. If you're triggering the download by interacting with an element:

1
2
3

   await page.click('#downloadButton');
   

If you're initiating the download programmatically:

1
2
3
4
5
6
7
8
9
10

   await page.evaluate(() => {
     const link = document.createElement('a');
     link.href = 'https://example.com/file-to-download.pdf';
     link.download = 'file.pdf';
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
   });