Selenium/WebdriverIO Chrome headless?

mpen picture mpen · Feb 17, 2017 · Viewed 13.5k times · Source

Is it possible to do automated browser testing with Selenium/WebdriverIO using Chrome in headless mode?

Supposedly Chrome --headless is a thing now, but I can't get their example working. I was hoping Selenium had an option for this?


I'm initializing WebdriverIO like so:

const WebdriverIO = require('webdriverio');

let driver = WebdriverIO.remote({
    desiredCapabilities: {
        browserName: browser, // "chrome" or "firefox"
    },
});

And I'm starting Selenium using selenium-standalone:

selenium-standalone start > /dev/null 2>&1

Answer

Oliver Joseph Ash picture Oliver Joseph Ash · Jun 2, 2017

WebdriverIO

Here is a working example with WebdriverIO: https://github.com/OliverJAsh/webdriverio-chrome-headless/blob/5f231990310023f63f9ea8581567e0d56e2d53ea/src/index.ts

The basic idea:

 import * as webdriverio from 'webdriverio';

// Headless is supported in Chrome >= 58. Not currently stable, so using dev
// build.
const CHROME_BIN_PATH = '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome';

const options = {
    desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions: {
            binary: CHROME_BIN_PATH,
            args: [
                'headless',
                // Use --disable-gpu to avoid an error from a missing Mesa
                // library, as per
                // https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md
                'disable-gpu',
            ],
        },
    },
};
webdriverio
    .remote(options)
    .init()
    .url('http://www.google.com')
    .getTitle().then(title => {
        console.log({ title });
    })
    .end();

WebDriverJS

Here is a working example with WebDriverJs (the official JavaScript client to WebDriver): https://github.com/OliverJAsh/webdriverjs-chrome-headless/blob/554ea2f150e962257119703c2473753b90842087/src/index.ts

The basic idea:

import * as webdriver from 'selenium-webdriver';
import * as chromeDriver from 'selenium-webdriver/chrome';

// Headless is supported in Chrome >= 58. Not currently stable, so using dev
// build.
const CHROME_BIN_PATH = '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome';

const options = new chromeDriver.Options();
options.setChromeBinaryPath(CHROME_BIN_PATH);
options.addArguments(
    'headless',
    // Use --disable-gpu to avoid an error from a missing Mesa library, as per
    // https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md
    'disable-gpu',
);

const driver = new webdriver.Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();