Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome download error when downloading file with Puppeteer

I have an application that shows a page, the user clicks on a button, and downloads a CSV file. I want to run this with Puppeteer.

Problem is that the CSV is downloaded empty and with an error. This happens both with headless true and false. The page finished loading, and I increased the timeout, but it still fails. What could be the issue?

enter image description here

const puppeteer = require('puppeteer');

(async () => {
    
    const browser = await puppeteer.launch({
       headless: false
    });

    const page = await browser.newPage();
    await page.goto('http://localhost:4400/login', { waitUntil: 'networkidle2' });    
    
    await page._client.send('Page.setDownloadBehavior', {
        behavior: 'allow',
        downloadPath: './',
    });

    await page.waitForSelector('#run-and-export');
    await page.click('#run-and-export');
  
    // file-downloaded is turned on when the file finished downloading (not to close the window)
    await page.waitForSelector('#file-downloaded', { timeout: 120000 }); 

    await browser.close();
    
})();

The code in the application that generates the file to download is an Angular service:

@Injectable({ 
    providedIn: 'root' 
})
export class DownloadService {

    downloadFile(content:any, fileName: string, mimeType: string){
    
        var blob = new Blob([(content)], {type: mimeType});
        var a = document.createElement('a');
        a.href = window.URL.createObjectURL(blob);
        a.download = fileName;
        a.click();

    }
}
like image 824
ps0604 Avatar asked Jul 16 '20 14:07

ps0604


People also ask

Why is Chrome not downloading my downloads?

This error means that your computer's security settings blocked the file. Learn more about blocked downloads. On Windows: Windows Attachment Manager could have removed the file you tried to download. To see what files you can download or why your file was blocked, check your Windows internet security settings.

Why do my browser downloads keep failing?

Check Your Internet Speed and Connection You need a stable internet connection for downloading files. So, you should first ensure that your internet connection is active and stable. To get started, test your Wi-Fi speed with a reliable speed test tool.

Why does my Chrome keep saying its downloading something?

Try clearing all your download history, and browsing data. (Settings >>> Privacy and Security >>> Clear Browsing Data). Make sure you tick at least Download History for All Time. If possible, try to clear everything just to be safe.


1 Answers

This is what made this work:

const downloadPath = path.resolve('/my/path');

await page._client.send('Page.setDownloadBehavior', {
    behavior: 'allow',
    downloadPath: downloadPath 
});
like image 94
ps0604 Avatar answered Oct 02 '22 14:10

ps0604