Teach

Automating Google Chrome with Node.js

Did you realize that Chrome now ships with the choice to run in headless mode? The characteristic is named Headless Chrome and it makes it tremendous simple for builders to configure a headless browser setting and run highly effective automated checks.

In this tutorial we’re going to speak about its numerous options and run a few cool examples. Let’s start!

What is Headless Chrome

Headless Chrome permits us to run the browser from the command line without truly opening a Chrome window. The simulated browser setting has the identical options as common Chrome and might load any web site or app we inform it to.

On prime of that, we have now numerous controls for interacting with the web page. We can click on parts, simulate keyboard enter, resize the browser, and much more. Using these controls we are able to write a wide range of useful scripts.

Here are some examples of duties normally carried out in a headless setting:

  • Generate screenshots and PDFs.
  • Navigate between hyperlinks and app states.
  • Automate consumer enter and kind validation testing.
  • Scrape knowledge from websites and SPAs.
  • Monitor efficiency.

Because Headless Chrome has a fairly low-level API, it is most well-liked to entry it through a library. For this tutorial, we’re going to use Puppeteer. The venture is maintained by the Chrome DevTools group and has a superb API that’s tremendous simple to work with.

Installation

To use Puppeteer you will have to have Node.js put in. You can learn how to do it right here. Note that each one the examples on this tutorial rely closely on the async/away syntax. It’s accessible solely within the more modern Node.js releases, so ensure you are working a model above v7.6.zero.

node --version
v8.three.zero

If you aren’t accustomed to the idea of async/await, we extremely suggest studying our article JavaScript Async Await Explained in 10 Minutes.

Go to your venture’s listing, initialize name and set up Puppeteer. You would possibly want sudo entry.

npm init
npm i puppeteer

Installation might take a few minutes. This is as a result of in contrast to most different frameworks for headless testing, Puppeteer robotically downloads a model of Chromium for you (about 100mb). That’s truly a really good characteristic since you will not should setup and preserve a neighborhood occasion of Chrome manually.

Create an index.js file to work on and were able to go!

Screen Capture

Taking screenshots with puppeteer may be very simple and there are many choices accessible for getting the precise outcomes we’d like. We’ll begin off with a primary instance and constructed upon that.

Below we merely begin a headless browser, open a web page, and take a screenshot of all of its contents.

const puppeteer = require('puppeteer');

(async () => 
  const browser = await puppeteer.launch();
  const web page = await browser.newPage();

  await web page.goto('https://tutorialzine.com');
  await web page.screenshot(
    path: 'landing-page.png',
    fullPage: true
  );

  browser.shut();
)();

To run our Puppeteer app we’ll simply name the index.js file with node. In an actual venture, you’ll most likely have to have some npm scripts that automate the method even additional.

node index.js

If there weren’t any errors we should always have a landing-page.png file in our working listing. By default the scale of a screenshot is 800px by 600px, however since we have set the flagfullPage to true, our picture has a width of 800px and a peak that matches all of the content material on the web page.

When taking the screenshot, Puppeteer will simulate a browser window with the specified width. If the web page we’re testing is responsive, we’ll get a snapshot of what it seems to be like at that viewport. We can change its dimensions through the setViewport technique.

await web page.setViewport(
  width: 1600, 
  peak: 1000
);

Using this technique we are able to modify our script to take a number of screenshots of assorted system sizes. This will enable us to shortly see if the responsiveness of our web page is working as supposed.

const puppeteer = require('puppeteer');

(async () => 
  const browser = await puppeteer.launch();
  const web page = await browser.newPage();

  // Ann array of viewport sizes for various gadgets.
  const viewports = [1600, 1000, 800, 600, 500];

  await web page.goto('https://tutorialzine.com');

  for(let i=zero; i < viewports.size; i++) 
    let vw = viewports[i];

    // The peak would not matter since we're screenshotting the total web page.
    await web page.setViewport(
      width: vw,
      peak: 1000
    );

    await web page.screenshot(
      path: `screen-$vw.png`,
      fullPage: true
    );
  

  browser.shut();
)();

Running this script will generate 5 photos, one for every viewport we have outlined.

There are many different issues you are able to do with the techniquescreenshot(). You can snap a remoted portion of the web page, change the standard and format of the picture, and extra. Check out the docs right here.

Interacting With The UI

With Puppeteer we are able to enter all the parts on the web page. This consists of all static content material like textual content and pictures, in addition to interactive parts reminiscent of hyperlinks, enter fields, buttons, and many others. Using automated controls we are able to scrape websites, check hyperlinks, and validate types.

For instance, here’s a script that hundreds our touchdown web page opens the search kind and searches for the time period ‘JavaScript’. We will run this instance with headless mode turned off in order that we are able to see what is going on.

const puppeteer = require('puppeteer');

(async () => 
  const browser = await puppeteer.launch(
    headless: false
  );
  const web page = await browser.newPage();

  // Open web page.
  await web page.goto('https://tutorialzine.com');

  // Show search kind.
  await web page.click on('.search-trigger');

  // Focus enter discipline.
  await web page.focus('#search-form-top enter');

  // Type in question.
  await web page.kind('JavaScript', delay: 200);

  // Submit the shape.
  const searchForm = await web page.$('#search-form-top');
  await searchForm.consider(searchForm => searchForm.submit());

  // Keep the browser open.
  // browser.shut();
)();

Since we’re utilizing the async/await syntax, all of the steps will execute within the right order and watch for one another to complete.