• Home
  • blog
  • Quick Tip: Getting Started with Headless Chrome in Node.js

Quick Tip: Getting Started with Headless Chrome in Node.js

Oftentimes in our line of work we need to be able to replicate a user journey repeatedly to make sure that our pages are offering a consistent experience as we make changes to our site. Critical to being able to accomplish this consistently and conveniently are libraries that allow us to script these types of tests, so that we can run assertions against them and maintain documentation around the results. Enter headless browsers: command line tools that provide you with the ability to script a user’s interactions across your site programmatically and capture the results to use in tests.

Many of us have been using PhantomJS, CasperJS, and other tools for years to do just this. But, as often is with love, our hearts can be bequeathed to another. As of Chrome 59 (60 for Windows users), Chrome ships with its own headless browser. And, although it doesn’t currently offer support for Selenium, it uses Chromium and the Blink engine, i.e. it is simulating an actual user experience in Chrome.

As ever, the code for this article can be found on our GitHub repo.

Run Headless Chrome From the Command Line

Running Headless Chrome from the command line is relatively easy. On a Mac, you can set an alias for Chrome and run using the —headless command line parameter

alias chrome="/Applications/Google Chrome”
chrome --headless --disable-gpu --remote-debugging-port=9090

On Linux, it’s even easier:

google-chrome --headless --disable-gpu --remote-debugging-port=9090
  • --headless: Runs without a UI or display server dependencies
  • --disable-gpu: Disables GPU hardware acceleration. This is temporarily needed for now.
  • --remote-debugging-port: Enables remote debug over HTTP on the specified port.

You can also interact with the page you are requesting, for example to print document.body.innerHTML to stdout you can do:

google-chrome --headless --disable-gpu --dump-dom

If you’re curious what else is possible, a full list of parameters can be found here.

Running Headless Chrome in Node.js

The focus of this article however, is not the command line, rather running Headless Chrome in Node.js. To do this, we’re going to need the following modules:

  • chrome-remote-interface: JavaScript API provides a simple abstraction of commands and notifications.
  • chrome-launcher: this allows us to launch Chrome from within Node across multiple platforms.

Continue reading %Quick Tip: Getting Started with Headless Chrome in Node.js%