Puppeteer is the NodeJs library that provides API to automate browsers. Puppeteer can be configured to run in headless and GUI mode.
In v3.0.0 puppeteer added experimental support for Firefox browser.
By default, puppeteer runs in headless mode using the Chromium browser. However, in the launch options you can pass {product: 'firefox'}
to launch the Firefox browser.
Let’s see step by step process
Prerequisite Node 10.18.1+
Navigate to the desired directory and run below command to create a fresh project
npm init -y
This is an important step and the one you might run into issues in case you are working on an existing project. Delete node_modules
directory if it already exists as the Firefox build is not downloaded if the puppeteer
package already exists in node_modules
.
If you are following along and created a fresh project then nothing to worry and you can directly execute below command.
PUPPETEER_PRODUCT=firefox npm install puppeteer@5.0.0
PUPPETEER_PRODUCT=firefox
tell puppeteer to download the latest Firefox Nightly binary for you instead of Chromium binary.
Once the installation is successful you can confirm the same using below command on the terminal in the current working directory.
ls -ltra node_modules/puppeteer
We will be using the below code as a starting point, borrowed from the previous tutorial. I have commented each line to make it easier for anybody who just started with Puppeteer.
// require puppeteer as dependency const puppeteer = require('puppeteer') // IIFE (Immediately Invoked Function Expression) ;(async () => { // launch browser instance const browser = await puppeteer.launch() // create new browser tab const page = await browser.newPage() // open desired page await page.goto('https://google.com') // close browser handle await browser.close() })()
To launch the Firefox browser, we can pass the option product: 'firefox'
and headless: false
in launch options object argument as follows
const browser = await puppeteer.launch({ product: 'firefox', headless: false })
You can even display the firefox browser logs on the terminal by defining option dumpio: true
.
Below is the final code.
const puppeteer = require('puppeteer') // IIFE (Immediately Invoked Function Expression) ;(async () => { // launch browser instance const browser = await puppeteer.launch({ product: 'firefox', headless: false }) // create new browser tab const page = await browser.newPage() // open desired page await page.goto('https://google.com') // close browser handle await browser.close() })()
To run the code, open a terminal window and navigate to project directory and type following command
node launch-firefox.js