WebDriverJS: Launch a browser


If you want to automate browsers, Selenium is your tool of choice.

There are several languages that you can use, but my focus will be on the JavaScript API, which is known as WebDriverJS.

Prerequisites

You’ll need Node.js installed. You can install it here or if you have homebrew installed:

$ brew install node

Then install selenium-webdriver:

$ npm install selenium-webdriver

Make sure that the version you install is supported by your version of node.

I’ll be assuming that you have a browser like Firefox installed. With Firefox 48+, you’ll need geckodriver installed additionally in order to control the browser.

Code

Launching a browser is very simple:

// launch-driver.js

const webdriver = require('selenium-webdriver');

// instantiate the firefox browser
const builder = new webdriver.Builder();
builder.forBrowser('firefox');
const driver = builder.build();

// go to the url
driver.get('http://example.com');

// print the title
driver.getTitle().then(title => console.log(title));

// close the browser
driver.quit();

Now you can run your script:

$ node launch-driver.js