I tried to install Puppeteer in a fresh NodeJS project. When I tried to launch a browser and take a screenshot it did not work.
I did:
- make new directory
- in terminal
npm init -y - create file
index.js - install puppeteer
npm i puppeteer - write this code in
index.js:import * as puppeteer from 'puppeteer'; (async ()=> { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://github.com/puppeteer/puppeteer'); await page.screenshot({path: 'my.png'}); // await browser.close(); }); - run with
node index.js
It neither opens the browser nor creates the screenshot.
You need
()after your IIFE:});should be})();. Otherwise, the function is defined but is never executed.A good way to debug this is to add a sanity check
console.log("running")at the top of the IIFE. If that doesn't run, but another sanity checkconsole.log("running")outside the IIFE does, you've discovered that the function was never called.Note that you're running headlessly, so after you fix the IIFE issue, it's still expected behavior that no visible browser will open. The expected behavior for your script is that it'll run, create a screenshot, and then hang forever because
browser.close()is commented out, requiring you to press Ctrl+c to terminate it. Usebrowser.launch({headless: false})if you want to see a browser open.I suggest the following Puppeteer boilerplate:
This is optimal for a number of reasons, major and minor:
try/catchlayer required for most scripts.In Node 20+ you can use top-level
awaitand avoid the IIFE.try/catchis useful in that case.