search developers
Edit

Browser

Understand what the Browser object is in Puppeteer/Playwright, how to create one, and a bit about how to interact with one.

In order to automate a browser in Playwright or Puppeteer, we need to open one up programmatically. Playwright supports Chromium, Firefox, and Webkit (Safari), while Puppeteer only supports Chromium based browsers. For ease of understanding, we've chosen to use Chromium in the Playwright examples to keep things working on the same plane.

Let's start by using the launch() function in the index.js file we created in the intro to this course:

import { chromium } from 'playwright';

await chromium.launch();

console.log('launched!');

When we run this code with the command node index.js, a browser will open up; however, we won't actually see anything. This is because the default mode of a browser after launch()ing it is headless, meaning that it has no visible UI.

If you run this code right now, it will hang. Use control^ + C to force quit the program.

Launch options

In order to see what's actually happening, we can pass an options object (Puppeteer, Playwright) with headless set to false.

import { chromium } from 'playwright';

await chromium.launch({ headless: false });

Now we'll actually see a browser open up.

Chromium browser opened by Puppeteer/Playwright

There are a whole lot more options that we can pass into the launch() function, which we'll be getting into a little bit later on.

Browser methods

The launch() function also returns an object representation of the browser that we can use to interact with the browser right from our code. This Browser object (Puppeteer, Playwright) has many functions which make it easy to do this. One of these functions is close(). Until now, we've been using control^ + C to force quit the process, but with this function, we'll no longer have to do that.

import { chromium } from 'playwright';

const browser = await chromium.launch({ headless: false });

// code will be here in the future

await browser.close();

Next up

Now that we can open a browser, let's move onto the next lesson where we will learn how to create pages and visit websites programmatically.