Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute single Javascript file with headless chrome from the command line

We use PhantomJS as simple test runner like this:

phantomjs path/to/test.js

Is there a similar way with headless chrome?

like image 331
iGEL Avatar asked Jun 16 '26 06:06

iGEL


1 Answers

Selenium WebDriver is a NPM package that can help you to run a headless browser.

Try the below example:

const chrome = require('selenium-webdriver/chrome');
const {Builder, By, Key, until} = require('selenium-webdriver');

const width = 640;
const height = 480;

let driver = new Builder()
    .forBrowser('chrome')
    .setChromeOptions(
        new chrome.Options().headless().windowSize({width, height}))
    .build();

driver.get('http://www.google.com/ncr')
    .then(_ =>
        driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN))
    .then(_ => driver.wait(until.titleIs('webdriver - Google Search'), 1000))
    .then(
        _ => driver.quit(),
        e => driver.quit().then(() => { throw e; }));

According to the API, the driver methods return Promises and, as a result, can be called using the async/await syntax:

const chrome = require('selenium-webdriver/chrome');
const {Builder, By, Key, until} = require('selenium-webdriver');

async function test() {
    const width = 640;
    const height = 480;

    let driver = new Builder()
        .forBrowser('chrome')
        .setChromeOptions(
            new chrome.Options().headless().windowSize({width, height}))
        .build();

    await driver.get('http://www.google.com/ncr')
    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN))
    await driver.wait(until.titleIs('webdriver - Google Search'), 1000))
    await driver.quit()
}

test();
like image 119
Vijendran Selvarajah Avatar answered Jun 17 '26 19:06

Vijendran Selvarajah