WebDriverJS: Launch a browser


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

There are several languages to choose from, but my focus will be on the JavaScript API, which is also known as WebDriverJS.

Prerequisites

Node.js

Install Node.js (see video). To install with homebrew:

brew install node

This should come with npm installed.

selenium-webdriver

Install selenium-webdriver:

npm install selenium-webdriver

Make sure the selenium-webdriver version is supported by your version of Node.js.

Firefox

Install Firefox. For Firefox 48+, you’ll need geckodriver in order to control the browser.

Script

Create script launch-driver.js:

touch launch-driver.js

Import selenium-webdriver:

const { Builder } = require('selenium-webdriver');

Build the driver:

const driver = new Builder().forBrowser('firefox').build();

Open page in browser:

driver.get('https://example.com');

Print the page title:

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

Close the browser:

driver.quit();

Here’s the full script:

// launch-driver.js

const { Builder } = require('selenium-webdriver');

// initialize the driver
const driver = new Builder().forBrowser('firefox').build();

// open the url
driver.get('https://example.com');

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

// close the browser
driver.quit();

Run the script:

node launch-driver.js

Examples

See WebDriverJS recipes.



Please support this site and join our Discord!