Skip to content

How to debug puppeteer and headless browsers

berstend̡̲̫̹̠̖͚͓̔̄̓̐̄͛̀͘ edited this page Nov 3, 2020 · 1 revision

Seeing what a headless browser is doing

Use remote debugging

const puppeteer = require("puppeteer-extra")

puppeteer
  .launch({
    headless: true,
    defaultViewport: null,
    args: [
      "--remote-debugging-port=9222",
      "--remote-debugging-address=0.0.0.0",
    ],
  })
  .then(async (browser) => {
    const page = await browser.newPage()
    await page.goto("https://bot.sannysoft.com")
    console.log(`Go to chrome://inspect in your regular Chrome. ✨`)
  })
  • Add the two --remote-debugging chrome args as shown above
  • Go to chrome://inspect in your regular Google Chrome
  • You can now debug and follow your headless browser with screencasting and devtools

Other ways to debug puppeteer code

1) Use node --inspect-brk (local)

Example

Save the following code to demo.js:

const puppeteer = require('puppeteer-extra')

puppeteer.launch().then(async browser => {
  const page = await browser.newPage()
  Object.assign(global, {browser, page})

  await page.goto('https://example.com')
  // await browser.close()
})

Run it using the --inspect-brk node flag:

$ node --inspect-brk demo.js
  • Go to about:inspect in a Chrome browser
  • Click inspect for the demo.js remote target
  • The debugger is pausing on the first line
    • In the sources tab, click the blue continue button on the right side
  • As we've commented out browser.close() you can continue working with page and browser
  • Go to the console tab and enter puppeteer commands (e.g. page.goto())

Note: You can use debugger statements in your code as well but promises won't resolve.

Make quick puppeteer debugging and exploration fun with an interactive REPL.

  • Can interrupt your code at anytime to start an interactive REPL in your console.
  • Adds convenience .repl() methods to Page and Browser instances.
  • Supports inspecting arbitrary objects and instances.
  • Features tab auto-completion for the available object properties and a colorized prompt.

Make puppeteer browser debugging possible from anywhere.

  • Creates a secure tunnel to make the devtools frontend (incl. screencasting) accessible from the public internet
  • Works for both headless and headful puppeteer instances, as well as within docker containers
  • Uses the already existing DevTools Protocol websocket connection from puppeteer
  • Features some convenience functions for using the devtools frontend locally