Puppeteer Examples Nodejs
puppeteer/puppeteer: Headless Chrome Node.js API – GitHub
API | FAQ | Contributing | Troubleshooting
Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.
What can I do?
Most things that you can do manually in the browser can be done using Puppeteer! Here are a few examples to get you started:
Generate screenshots and PDFs of pages.
Crawl a SPA (Single-Page Application) and generate pre-rendered content (i. e. “SSR” (Server-Side Rendering)).
Automate form submission, UI testing, keyboard input, etc.
Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
Capture a timeline trace of your site to help diagnose performance issues.
Test Chrome Extensions.
Give it a spin:
Getting Started
Installation
To use Puppeteer in your project, run:
npm i puppeteer
# or “yarn add puppeteer”
Note: When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API. To skip the download, download into another path, or download a different browser, see Environment variables.
puppeteer-core
Since version 1. 7. 0 we publish the puppeteer-core package,
a version of Puppeteer that doesn’t download any browser by default.
npm i puppeteer-core
# or “yarn add puppeteer-core”
puppeteer-core is intended to be a lightweight version of Puppeteer for launching an existing browser installation or for connecting to a remote one. Be sure that the version of puppeteer-core you install is compatible with the
browser you intend to connect to.
See puppeteer vs puppeteer-core.
Usage
Puppeteer follows the latest maintenance LTS version of Node.
Note: Prior to v1. 18. 1, Puppeteer required at least Node v6. 4. 0. Versions from v1. 1 to v2. 1. 0 rely on
Node 8. 9. 0+. Starting from v3. 0 Puppeteer starts to rely on Node 10. 1+. All examples below use async/await which is only supported in Node v7. 6. 0 or greater.
Puppeteer will be familiar to people using other browser testing frameworks. You create an instance
of Browser, open pages, and then manipulate them with Puppeteer’s API.
Example – navigating to and saving a screenshot as
Save file as
const puppeteer = require(‘puppeteer’);
(async () => {
const browser = await ();
const page = await wPage();
await (”);
await reenshot({ path: ”});
await ();})();
Execute script on the command line
Puppeteer sets an initial page size to 800×600px, which defines the screenshot size. The page size can be customized with tViewport().
Example – create a PDF.
await (”, {
waitUntil: ‘networkidle2’, });
await ({ path: ”, format: ‘a4’});
See () for more information about creating pdfs.
Example – evaluate script in the context of the page
// Get the “viewport” of the page, as reported by the page.
const dimensions = await page. evaluate(() => {
return {
width: ientWidth,
height: ientHeight,
deviceScaleFactor: vicePixelRatio, };});
(‘Dimensions:’, dimensions);
See Page. evaluate() for more information on evaluate and related methods like evaluateOnNewDocument and exposeFunction.
Default runtime settings
1. Uses Headless mode
Puppeteer launches Chromium in headless mode. To launch a full version of Chromium, set the headless option when launching a browser:
const browser = await ({ headless: false}); // default is true
2. Runs a bundled version of Chromium
By default, Puppeteer downloads and uses a specific version of Chromium so its API
is guaranteed to work out of the box. To use Puppeteer with a different version of Chrome or Chromium,
pass in the executable’s path when creating a Browser instance:
const browser = await ({ executablePath: ‘/path/to/Chrome’});
You can also use Puppeteer with Firefox Nightly (experimental support). See () for more information.
See this article for a description of the differences between Chromium and Chrome. This article describes some differences for Linux users.
3. Creates a fresh user profile
Puppeteer creates its own browser user profile which it cleans up on every run.
Resources
API Documentation
Examples
Community list of Puppeteer resources
Debugging tips
Turn off headless mode – sometimes it’s useful to see what the browser is
displaying. Instead of launching in headless mode, launch a full version of
the browser using headless: false:
const browser = await ({ headless: false});
Slow it down – the slowMo option slows down Puppeteer operations by the
specified amount of milliseconds. It’s another way to help see what’s going on.
const browser = await ({
headless: false,
slowMo: 250, // slow down by 250ms});
Capture console output – You can listen for the console event.
This is also handy when debugging code in page. evaluate():
(‘console’, (msg) => (‘PAGE LOG:’, ()));
await page. evaluate(() => (`url is ${}`));
Use debugger in application code browser
There are two execution context: that is running test code, and the browser
running application code being tested. This lets you debug code in the
application code browser; ie code inside evaluate().
Use {devtools: true} when launching Puppeteer:
const browser = await ({ devtools: true});
Change default test timeout:
jest: tTimeout(100000);
jasmine: FAULT_TIMEOUT_INTERVAL = 100000;
mocha: this. timeout(100000); (don’t forget to change test to use function and not ‘=>’)
Add an evaluate statement with debugger inside / add debugger to an existing evaluate statement:
await page. evaluate(() => {
debugger;});
The test will now stop executing in the above evaluate statement, and chromium will stop in debug mode.
Use debugger in
This will let you debug test code. For example, you can step over await () in the script and see the click happen in the application code browser.
Note that you won’t be able to run await () in
DevTools console due to this Chromium bug. So if
you want to try something out, you have to add it to your test file.
Add debugger; to your test, eg:
debugger;
await (‘a[target=_blank]’);
Set headless to false
Run node –inspect-brk, eg node –inspect-brk node_modules/ tests
In Chrome open chromeinspect/#devices and click inspect
In the newly opened test browser, type F8 to resume test execution
Now your debugger will be hit and you can debug in the test browser
Enable verbose logging – internal DevTools protocol traffic
will be logged via the debug module under the puppeteer namespace.
# Basic verbose logging
env DEBUG=”puppeteer:*” node
# Protocol traffic can be rather noisy. This example filters out all Network domain messages
env DEBUG=”puppeteer:*” env DEBUG_COLORS=true node 2>&1 | grep -v ‘”Network’
Debug your Puppeteer (node) code easily, using ndb
npm install -g ndb (or even better, use npx! )
add a debugger to your Puppeteer (node) code
add ndb (or npx ndb) before your test command. For example:
ndb jest or ndb mocha (or npx ndb jest / npx ndb mocha)
debug your test inside chromium like a boss!
Usage with TypeScript
We have recently completed a migration to move the Puppeteer source code from JavaScript to TypeScript and as of version 7. 1 we ship our own built-in type definitions.
If you are on a version older than 7, we recommend installing the Puppeteer type definitions from the DefinitelyTyped repository:
npm install –save-dev @types/puppeteer
The types that you’ll see appearing in the Puppeteer source code are based off the great work of those who have contributed to the @types/puppeteer package. We really appreciate the hard work those people put in to providing high quality TypeScript definitions for Puppeteer’s users.
Contributing to Puppeteer
Check out contributing guide to get an overview of Puppeteer development.
Q: Who maintains Puppeteer?
The Chrome DevTools team maintains the library, but we’d love your help and expertise on the project!
See Contributing.
Q: What is the status of cross-browser support?
Official Firefox support is currently experimental. The ongoing collaboration with Mozilla aims to support common end-to-end testing use cases, for which developers expect cross-browser coverage. The Puppeteer team needs input from users to stabilize Firefox support and to bring missing APIs to our attention.
From Puppeteer v2. 0 onwards you can specify ({product: ‘firefox’}) to run your Puppeteer scripts in Firefox Nightly, without any additional custom patches. While an older experiment required a patched version of Firefox, the current approach works with “stock” Firefox.
We will continue to collaborate with other browser vendors to bring Puppeteer support to browsers such as Safari.
This effort includes exploration of a standard for executing cross-browser commands (instead of relying on the non-standard DevTools Protocol used by Chrome).
Q: What are Puppeteer’s goals and principles?
The goals of the project are:
Provide a slim, canonical library that highlights the capabilities of the DevTools Protocol.
Provide a reference implementation for similar testing libraries. Eventually, these other frameworks could adopt Puppeteer as their foundational layer.
Grow the adoption of headless/automated browser testing.
Help dogfood new DevTools Protocol catch bugs!
Learn more about the pain points of automated browser testing and help fill those gaps.
We adapt Chromium principles to help us drive product decisions:
Speed: Puppeteer has almost zero performance overhead over an automated page.
Security: Puppeteer operates off-process with respect to Chromium, making it safe to automate potentially malicious pages.
Stability: Puppeteer should not be flaky and should not leak memory.
Simplicity: Puppeteer provides a high-level API that’s easy to use, understand, and debug.
Q: Is Puppeteer replacing Selenium/WebDriver?
No. Both projects are valuable for very different reasons:
Selenium/WebDriver focuses on cross-browser automation; its value proposition is a single standard API that works across all major browsers.
Puppeteer focuses on Chromium; its value proposition is richer functionality and higher reliability.
That said, you can use Puppeteer to run tests against Chromium, e. g. using the community-driven jest-puppeteer. While this probably shouldn’t be your only testing solution, it does have a few good points compared to WebDriver:
Puppeteer requires zero setup and comes bundled with the Chromium version it works best with, making it very easy to start with. At the end of the day, it’s better to have a few tests running chromium-only, than no tests at all.
Puppeteer has event-driven architecture, which removes a lot of potential flakiness. There’s no need for evil “sleep(1000)” calls in puppeteer scripts.
Puppeteer runs headless by default, which makes it fast to run. Puppeteer v1. 5. 0 also exposes browser contexts, making it possible to efficiently parallelize test execution.
Puppeteer shines when it comes to debugging: flip the “headless” bit to false, add “slowMo”, and you’ll see what the browser is doing. You can even open Chrome DevTools to inspect the test environment.
Q: Why doesn’t Puppeteer work with Chromium
We see Puppeteer as an indivisible entity with Chromium. Each version of Puppeteer bundles a specific version of Chromium – the only version it is guaranteed to work with.
This is not an artificial constraint: A lot of work on Puppeteer is actually taking place in the Chromium repository. Here’s a typical story:
A Puppeteer bug is reported: It turned out this is an issue with the DevTools protocol, so we’re fixing it in Chromium: Once the upstream fix is landed, we roll updated Chromium into Puppeteer:
However, oftentimes it is desirable to use Puppeteer with the official Google Chrome rather than Chromium. For this to work, you should install a puppeteer-core version that corresponds to the Chrome version.
For example, in order to drive Chrome 71 with puppeteer-core, use chrome-71 npm tag:
npm install puppeteer-core@chrome-71
Q: Which Chromium version does Puppeteer use?
Look for the chromium entry in To find the corresponding Chromium commit and version number, search for the revision prefixed by an r in OmahaProxy’s “Find Releases” section.
Q: Which Firefox version does Puppeteer use?
Since Firefox support is experimental, Puppeteer downloads the latest Firefox Nightly when the PUPPETEER_PRODUCT environment variable is set to firefox. That’s also why the value of firefox in is latest — Puppeteer isn’t tied to a particular Firefox version.
To fetch Firefox Nightly as part of Puppeteer installation:
PUPPETEER_PRODUCT=firefox npm i puppeteer
Q: What’s considered a “Navigation”?
From Puppeteer’s standpoint, “navigation” is anything that changes a page’s URL.
Aside from regular navigation where the browser hits the network to fetch a new document from the web server, this includes anchor navigations and History API usage.
With this definition of “navigation, ” Puppeteer works seamlessly with single-page applications.
Q: What’s the difference between a “trusted” and “untrusted” input event?
In browsers, input events could be divided into two big groups: trusted vs. untrusted.
Trusted events: events generated by users interacting with the page, e. using a mouse or keyboard.
Untrusted event: events generated by Web APIs, e. eateEvent or () methods.
Websites can distinguish between these two groups:
using an Trusted event flag
sniffing for accompanying events. For example, every trusted ‘click’ event is preceded by ‘mousedown’ and ‘mouseup’ events.
For automation purposes it’s important to generate trusted events. All input events generated with Puppeteer are trusted and fire proper accompanying events. If, for some reason, one needs an untrusted event, it’s always possible to hop into a page context with page. evaluate and generate a fake event:
document. querySelector(‘button[type=submit]’)();});
Q: What features does Puppeteer not support?
You may find that Puppeteer does not behave as expected when controlling pages that incorporate audio and video. (For example, video playback/screenshots is likely to fail. ) There are two reasons for this:
Puppeteer is bundled with Chromium — not Chrome — and so by default, it inherits all of Chromium’s media-related limitations. This means that Puppeteer does not support licensed formats such as AAC or H. 264. (However, it is possible to force Puppeteer to use a separately-installed version Chrome instead of Chromium via the executablePath option to You should only use this configuration if you need an official release of Chrome that supports these media formats. )
Since Puppeteer (in all configurations) controls a desktop version of Chromium/Chrome, features that are only supported by the mobile version of Chrome are not supported. This means that Puppeteer does not support HTTP Live Streaming (HLS).
Q: I am having trouble installing / running Puppeteer in my test environment. Where should I look for help?
We have a troubleshooting guide for various operating systems that lists the required dependencies.
Q: Chromium gets downloaded on every npm ci run. How can I cache the download?
The default download path is node_modules/puppeteer/ However, you can change that path with the PUPPETTER_DOWNLOAD_PATH environment variable.
Puppeteer uses that variable to resolve the Chromium executable location during launch, so you don’t need to specify PUPPETEER_EXECUTABLE_PATH as well.
For example, if you wish to keep the Chromium download in ~/
export PUPPETEER_DOWNLOAD_PATH=~/
npm ci
# by default the Chromium executable path is inferred
# from the download path
npm test
# a new run of npm ci will check for the existence of
# Chromium in ~/
Q: How do I try/test a prerelease version of Puppeteer?
You can check out this repo or install the latest prerelease from npm:
npm i –save puppeteer@next
Please note that prerelease may be unstable and contain bugs.
Q: I have more questions! Where do I ask?
There are many ways to get help on Puppeteer:
bugtracker
Stack Overflow
Make sure to search these channels before posting your question.
puppeteer JavaScript and Node.js code examples | Tabnine
Best JavaScript code snippets using puppeteer(Showing top 15 results out of 873)(async () => {
const browser = await ()
const page = await wPage()
await (”)
await (‘. playableTile__artwork’)
await reenshot({ path: ”})
await ()})()
beforeAll(async () => {
browser = await ()
page = await wPage()
await ({ path: ”})})
async getPage() {
if () {
return;}
const browser = await tBrowser();
= await wPage();
async stop() {
await ();
return (() => ());}
(async () => {
await tViewport({ width: 1280, height: 800})
await (”, { waitUntil: ‘networkidle2’})
await page. waitForSelector(”)
await reenshot({ path: screenshot})
await ()
(‘See screen shot: ‘ + screenshot)})()
const browser = await ({ headless: true})
await (‘#login_field’, )
await (‘#password’, )
await (‘[name=”commit”]’)
await page. waitForNavigation()
()
(‘See screenshot: ‘ + screenshot)})()
const browser = await ({args: [‘–no-sandbox’]});
const page = await wPage();
await (”);
await init(browser, page, observer, options);})()((observer));
before(async () => {
await tExtraHTTPHeaders({ ‘Accept-Language’: ‘en-GB, en-US;q=0. 9, en;q=0. 8’})
await tViewport({ width: 1280, height: 800})})
(‘dialog’, async dialog => {
(ssage())
await dialog. dismiss()})
await page. evaluate(() => alert(‘This message is inside an alert box’))
await page. emulate(iPhone)
await reenshot({
path: ”,
fullPage: true})
(await ())
async start() {
await (‘trix-editor’)
await (‘Just adding a title’)
const title = await ()
(title)
await tViewport(viewPort)
await reenshot(options)
await tViewport({ width: 800, height: 600})
await (132, 103, { button: ‘left’})
await ()})()
Getting to Know Puppeteer Using Practical Examples – Nitay …
An overview, concrete guide and kinda cheat sheet for the popular browser automation library, based on, which provides a high-level API over the Chrome DevTools Protocol.
Contents
How to Install
Library Package
Product Package
Interacting Browser
Launching Chromium
Connecting Chromium
Launching Firefox
Browser Context
Headful Mode
Debugging
Interacting Page
Navigating by URL
Emulating Devices
Handling Events
Operating Mouse
Operating Keyboard
Taking Screenshots
Generating PDF
Faking Geolocation
Accessibility
Code Coverage
Measuring Performance
Summary
VS Code Snippets
Puppeteer is a project from the Google Chrome team which enables us to control a Chrome (or any other Chrome DevTools Protocol based browser) and execute common actions, much like in a real browser – programmatically, through a decent API.
Put simply, it’s a super useful and easy tool for automating, testing and scraping web pages over a headless mode or headful either.
In this article we’re going to try out Puppeteer and demonstrate a variety of the available capabilities, through concrete examples.
Disclaimer: This article doesn’t claim to replace the official documentation but rather elaborate it – you definitely should go over it in order to be aligned with the most updated API specification.
Sponsor:
Active Reliability for Modern DevOps Teams
Checkly does in-depth API monitoring and synthetic monitoring using Puppeteer. It lets us run Puppeteer scripts every couple of minutes or trigger them from the continuous integration pipeline. Check it out during the article or afterwards.
To begin with, we’ll have to install one of Puppeteer’s packages.
A lightweight package, called puppeteer-core, which is a library that interacts with any browser that’s based on DevTools protocol – without actually installing Chromium. It comes in handy mainly when we don’t need a downloaded version of Chromium, for instance, bundling this library within a project that interacts with a browser remotely.
In order to install, just run:
npm install puppeteer-core
The main package, called puppeteer, which is actually a full product for browser automation on top of puppeteer-core. Once it’s installed, the most recent version of Chromium is placed inside node_modules, what guarantees that the downloaded version is compatible with the host operating system.
Simply run the following to install:
npm install puppeteer
Now, we’re absolutely ready to go!
As mentioned before, Puppeteer is just an API over the Chrome DevTools Protocol. Naturally, it should have a Chromium instance to interact with. This is the reason why Puppeteer’s ecosystem provides methods to launch a new Chromium instance and connect an existing instance also.
Let’s examine a few cases.
The easiest way to interact with the browser is by launching a Chromium instance using Puppeteer:
The launch method initializes the instance at first, and then attaching Puppeteer to that.
Notice this method is asynchronous (like most Puppeteer’s methods) which, as we know, returns a Promise. Once it’s resolved, we get a browser instance that represents our initialized instance.
Sometimes we want to interact with an existing Chromium instance – whether using puppeteer-core or just attaching a remote instance:
Well, it’s easy to see that we use chrome-launcher in order to launch a Chrome instance manually.
Then, we simply fetch the webSocketDebuggerUrl value of the created instance.
The connect method attaches the instance we just created to Puppeteer. All we’ve to do is supplying the WebSocket endpoint of our instance.
Note: Of course, chrome-launcher is only to demonstrate an instance creation. We absolutely could connect an instance in other ways, as long as we have the appropriate WebSocket endpoint.
Some of you might wonder – could Puppeteer interact with other browsers besides Chromium?
Although there are projects that claim to support the variety browsers – the official team has started to maintain an experimental project that interacts with Firefox, specifically:
npm install puppeteer-firefox
Update: puppeteer-firefox was an experimental package to examine communication with an outdated Firefox fork, however, this project is no longer maintained. Presently, the way to go is by setting the PUPPETEER_PRODUCT environment variable to firefox and so fetching the binary of Firefox Nightly.
We can easily do that as part of the installation:
PUPPETEER_PRODUCT=firefox npm install puppeteer
Alternatively, we can use the BrowserFetcher to fetch the binary.
Once we’ve the binary, we merely need to change the product to “firefox” whereas the rest of the lines remain the same – what means we’re already familiar with how to launch the browser:
⚠️ Pay attention – the API integration isn’t totally ready yet and implemented progressively. Also, it’s better to check out the implementation status here.
Imagine that instead of recreating a browser instance each time, which is pretty expensive operation, we could use the same instance but separate it into different individual sessions which belong to this shared browser.
It’s actually possible, and these sessions are known as Browser Contexts.
A default browser context is created as soon as creating a browser instance, but we can create additional browser contexts as necessary:
Apart from the fact that we demonstrate how to access each context, we need to know that the only way to terminate the default context is by closing the browser instance – which, in fact, terminates all the contexts that belong to the browser.
Better yet, the browser context also come in handy when we want to apply a specific configuration on the session isolatedly – for instance, granting additional permissions.
As opposed to the headless mode – which merely uses the command line,
the headful mode opens the browser with a graphical user interface during the instruction:
Because of the fact that the browser is launched in headless mode by default, we demonstrate how to launch it in a headful way.
In case you wonder – headless mode is mostly useful for environments that don’t really need the UI or neither support such an interface. The cool thing is that we can headless almost everything in Puppeteer.
Note: We’re going to launch the browser in a headful mode for most of the upcoming examples, which will allow us to notice the result clearly.
When writing code, we should be aware of what kinds of ways are available to debug our program. The documentation lists several tips about debugging Puppeteer.
Let’s cover the core principles:
1️⃣ – Checking how the browser is operated
That’s fairly probable we would like to see how our script instructs the browser and what’s actually displayed, at some point.
The headful mode, which we’re already familiar with, helps us to practically do that:
Beyond that the browser is truly opened, we can notice now the operated instructions clearly – due to slowMo which slows down Puppeteer when performing each operation.
2️⃣ – Debugging our application code in the browser
In case we want to debug the application itself in the opened browser – it basically means to open the DevTools and start debugging as usual:
Notice that we use devtools which launches the browser in a headful mode by default and opens the DevTools automatically.
On top of that, we utilize waitForTarget in order to hold the browser process until we terminate it explicitly.
Apparently – some of you may wonder if it’s possible to sleep the browser with a specified time period, so:
The first approach is merely a function that resolves a promise when setTimeout finishes.
The second approach, however, is much simpler but demands having a page instance (we’ll get to that later).
3️⃣ – Debugging the process that uses Puppeteer
As we know, Puppeteer is executed in a process – which is absolutely separated from the browser process.
Hence, in this case, we should treat it as much as we debug a regular application.
Whether we connect to an inspector client or prefer using ndb –
it’s all about placing the breakpoints right before Puppeteer’s operation. Adding them programmatically is possible either, simply by inserting the debugger; statement, obviously.
Now that Puppeteer is attached to a browser instance – which, as we already mentioned, represents our browser instance (Chromium, Firefox, whatever),
allows us creating easily a page (or multiple pages):
In the code example above we plainly create a new page by invoking the newPage method. Notice it’s created on the default browser context.
Basically, Page is a class that represents a single tab in the browser (or an extension background).
As you guess, this class provides handy methods and events in order to interact with the page (such as selecting elements, retrieving information, waiting for elements, etc. ).
Well, it’s about time to present a list of practical examples, as promised. To do this, we’re going to scrape data from the official Puppeteer website and operate it.
One of the earliest things is, intuitively, instructing the blank page to navigate to a specified URL:
We use goto to drive the created page to navigate Puppeteer’s website. Afterward, we just take the title of Page’s main frame, print it, and expect to get that as an output:
Navigating by a URL and scraping the title
As we notice, the title is unexpectedly missing.
This example shows us which there’s no guarantee that our page would render the selected element at the right moment, and if anything.
To clarify – possible reasons could be that the page is loaded slowly, part of the page is lazy-loaded, or perhaps it’s navigated immediately to another page.
That’s exactly why Puppeteer provides methods to wait for stuff like elements, navigation, functions, requests, responses or simply a certain predicate – mainly to deal with an asynchronous flow.
Anyway, it turns out that Puppeteer’s website has an entry page, which immediately redirects us to the well-known website’s index page.
The thing is, that entry page in question doesn’t render a title meta element:
Evaluating the title meta element
When navigating to Puppeteer’s website, the title element is evaluated as an empty string. However, a few moments later, the page is really navigated to the website’s index page and rendered with a title.
This means that the invoked title method is actually applied too early, on the entry page, instead of the website’s index page. Thus, the entry page is considered as the first main frame, and eventually its title, which is an empty string, is returned.
Let’s solve that case in a simple way:
All we do, is instructing Puppeteer to wait until the page renders a title meta element, which is achieved by invoking waitForSelector. This method basically waits until the selected element is rendered within the page.
In that way – we can easily deal with asynchronous rendering and ensure that elements are visible on the page.
Puppeteer’s library provides tools for approximating how the page looks and behaves on various devices, which are pretty useful when testing a website’s responsiveness.
Let’s emulate a mobile device and navigate to the official website:
We choose to emulate an iPhone X – which means changing the user agent appropriately.
Furthermore, we adjust the viewport size according to the display points that appear here.
It’s easy to understand that setUserAgent defines a specific user agent for the page, whereas setViewport modifies the viewport definition of the page. In case of multiple pages, each one has its own user agent and viewport definition.
Here’s the result of the code example above:
Emulating an iPhone X
Indeed, the console panel shows us that the page is opened with the right user agent and viewport size.
The truth is that we don’t have to specify the iPhone X’s descriptions explicitly, because the library arrives with a built-in list of device descriptors. On top of that, it provides a method called emulate which is practically a shortcut for invoking setUserAgent and setViewport, one after another.
Let’s use that:
It’s merely changed to pass the boilerplate descriptor to emulate (instead of declaring that explicitly).
Notice we import the descriptors out of puppeteer/DeviceDescriptors.
The Page class supports emitting of various events by actually extending the ’s EventEmitter object.
This means we can use the natively supported methods in order to handle these events – such as: on, once, removeListener and so on.
Here’s the list of the supported events:
From looking at the list above – we clearly understand that the supported events include aspects of loading, frames, metrics, console, errors, requests, responses and even more!
Let’s simulate and trigger part of the events by adding this script:
As we probably know, evaluate just executes the supplied script within the page context.
Though, the output is going to reflect the events we listen:
Listening the page events
In case you wonder – it’s possible to listen for custom events that are triggered in the page. Basically it means to define the event handler on page’s window using the exposeFunction method.
Check out this example to understand exactly how to implement it.
In general, the mouse controls the motion of a pointer in two dimensions within a viewport.
Unsurprisingly, Puppeteer represents the mouse by a class called Mouse.
Moreover, every Page instance has a Mouse – which allows performing operations such as changing its position and clicking within the viewport.
Let’s start with changing the mouse position:
The scenario we simulate is moving the mouse over the second link of the left API sidebar.
We set a viewport size and wait explicitly for the sidebar component to ensure it’s really rendered.
Then, we invoke move in order to position the mouse with appropriate coordinates, that actually represent the center of the second link.
This is the expected result:
Hovering the second link
Although it’s hard to see, the second link is hovered as we planned.
The next step is simply clicking on the link by the respective coordinates:
Instead of changing the position explicitly, we just use click – which basically triggers mousemove, mousedown and mouseup events, one after another.
Note: We delay the pressing in order to demonstrate how to modify the click behavior, nothing more. It’s worth pointing out that we can also control the mouse buttons (left, center, right) and the number of clicks.
Another nice thing is the ability to simulate a drag and drop behavior easily:
All we do is using the Mouse methods for grabbing the mouse, from one position to another, and afterward releasing it.
The keyboard is another way to interact with the page, mostly for input purposes.
Similar to the mouse, Puppeteer represents the keyboard by a class called Keyboard – and every Page instance holds such an instance.
Let’s type some text within the search input:
Notice that we wait for the toolbar (instead of the API sidebar).
Then, we focus the search input element and simply type a text into it.
On top of typing text, it’s obviously possible to trigger keyboard events:
Basically, we press ArrowDown twice and Enter in order to choose the third search result.
See that in action:
Choosing a search result using the keyboard
By the way, it’s nice to know that there is a list of the key codes.
Taking screenshots through Puppeteer is a quite easy mission.
The API provides us a dedicated method for that:
As we see, the screenshot method makes all the charm – whereas we just have to insert a path for the output.
Moreover, it’s also possible to control the type, quality and even clipping the image:
Here’s the output:
Capturing an area within the page
Puppeteer is either useful for generating a PDF file from the page content.
Let’s demonstrate that:
Running the pdf method simply generates us the following file:
Generating a PDF file from the content
Many websites customize their content based on the user’s geolocation.
Modifying the geolocation of a page is pretty obvious:
First, we grants the browser context the appropriate permissions. Then, we use setGeolocation to override the current geolocation with the coordinates of the north pole.
Here’s what we get when printing the location through navigator:
Changing the geolocation of the page
The accessibility tree is a subset of the DOM that includes only elements with relevant information for assistive technologies such as screen readers, voice controls and so on.
Having the accessibility tree means we can analyze and test the accessibility support in the page.
When it comes to Puppeteer, it enables to capture the current state of the tree:
The snapshot doesn’t pretend to be the full tree, but rather including just the interesting nodes (those which are acceptable by most of the assistive technologies).
Note: We can obtain the full tree through setting interestingOnly to false.
The code coverage feature was introduced officially as part of Chrome v59 – and provides the ability to measure how much code is being used, compared to the code that is actually loaded.
In this manner, we can reduce the dead code and eventually speed up the loading time of the pages.
With Puppeteer, we can manipulate the same feature programmatically:
We instruct Puppeteer to gather coverage information for JavaScript and CSS files, until the page is loaded.
Thereafter, we define calculateUsedBytes which goes through a collected coverage data and calculates how many bytes are being used (based on the coverage).
At last, we merely invoke the created function on both coverages.
Let’s look at the output:
As expected, the output contains usedBytes and totalBytes for each file.
One objective of measuring performance in terms of websites is to analyze how a page performs, during load and runtime – intending to make it faster.
Let’s see how we use Puppeteer to measure our page performance:
1️⃣ – Analyzing load time through metrics
Navigation Timing is a Web API that provides information and metrics relating to page navigation and load events, and accessible by rformance.
In order to benefit from it, we should evaluate this API within the page context:
Notice that if evaluate receives a function which returns a non-serializable value – then evaluate returns eventually undefined.
That’s exactly why we stringify rformance when evaluating within the page context.
The result is transformed into a comfy object, which looks like the following:
Now we can simply combine these metrics and calculate different load times over the loading timeline.
For instance, loadEventEnd – navigationStart represents the time since the navigation started until the page is loaded.
Note: All explanations about the different timings above are available here.
2️⃣ – Analyzing runtime through metrics
As far as the runtime metrics, unlike load time, Puppeteer provides a neat API:
We invoke the metrics method and get the following result:
The interesting metric above is apparently JSHeapUsedSize which represents, in other words, the actual memory usage of the page.
Notice that the result is actually the output of tMetrics, which is part of Chrome DevTools Protocol.
3️⃣ – Analyzing browser activities through tracing
Chromium Tracing is a profiling tool that allows recording what the browser is really doing under the hood – with an emphasis on every thread, tab, and process.
And yet, it’s reflected in Chrome DevTools as part of the Timeline panel.
Furthermore, this tracing ability is possible with Puppeteer either – which, as we might guess, practically uses the Chrome DevTools Protocol.
For example, let’s record the browser activities during navigation:
When the recording is stopped, a file called is created and contains the output that looks like:
Now that we’ve the trace file, we can open it using Chrome DevTools, chrometracing or Timeline Viewer.
Here’s the Performance panel after importing the trace file into the DevTools:
Importing a trace file
We introduced today the Puppeteer’s API through concrete examples.
Let’s recap the main points:
Puppeteer is a library for automating, testing and scraping web pages on top of the Chrome DevTools Protocol.
Puppeteer’s ecosystem provides a lightweight package, puppeteer-core, which is a library for browser automation – that interacts with any browser, which is based on DevTools protocol, without installing Chromium.
Puppeteer’s ecosystem provides a package, which is actually the full product, that installs Chromium in addition to the browser automation library.
Puppeteer provides the ability to launch a Chromium browser instance or just connect an existing instance.
Puppeteer’s ecosystem provides an experimental package, puppeteer-firefox, that interacts with Firefox.
The browser context allows separating different sessions for a single browser instance.
Puppeteer launches the browser in a headless mode by default, which merely uses the command line. Also – a headful mode, for opening the browser with a GUI, is supported either.
Puppeteer provides several ways to debug our application in the browser, whereas, debugging the process that executes Puppeteer is obviously the same as debugging a regular process.
Puppeteer allows navigating to a page by a URL and operating the page through the mouse and keyboard.
Puppeteer allows examining a page’s visibility, behavior and responsiveness on various devices.
Puppeteer allows taking screenshots of the page and generating PDFs from the content, easily.
Puppeteer allows analyzing and testing the accessibility support in the page.
Puppeteer allows speeding up the page performance by providing information about the dead code, handy metrics and manually tracing ability.
And finally, Puppeteer is a powerful browser automation tool with a pretty simple API.
A decent number of capabilities are supported, including such we haven’t covered at all – and that’s why your next step could definitely be the official documentation.
Here’s attached the final project:
Well, if you wish to get some useful code snippets of Puppeteer API for Visual Studio Code – then the following extension might interest you:
Using the snippets to generate a basic Puppeteer script
You’re welcome to take a look at the extension page.
If you like this information and find it interesting or useful – share it