RobH
RobH

Reputation: 1639

How do you run Selenium headless in PHP?

We'd like to run our Selenium tests along with our other unit tests in our build scripts, but given that the builds are running on Jenkins, which is running as a service, the tests need to be run headless. Our Selenium tests are written in PHP, and everything that I've seen so far seems to apply to JavaScript or Python.

Is there any way for us to run our PHP Selenium tests headless (preferably using the same drivers as when not running headless so we can detect problems with specific browsers)?

Upvotes: 3

Views: 4120

Answers (2)

Ondrej Machulda
Ondrej Machulda

Reputation: 1010

This has been improved in php-webdriver 1.11.0 (2021-05-03).

Start headless Chrome

$chromeOptions = new ChromeOptions();
$chromeOptions->addArguments(['--headless']);

$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability(ChromeOptions::CAPABILITY_W3C, $chromeOptions);

// Start the browser with $capabilities
// A) When using RemoteWebDriver::create()
$driver = RemoteWebDriver::create($serverUrl, $capabilities);
// B) When using ChromeDriver::start to start local Chromedriver
$driver = ChromeDriver::start($capabilities);

See php-webdriver wiki article for more Chrome examples.

Start headless Firefox

$firefoxOptions = new FirefoxOptions();
$firefoxOptions->addArguments(['-headless']);

$capabilities = DesiredCapabilities::firefox();
$capabilities->setCapability(FirefoxOptions::CAPABILITY, $firefoxOptions);

// Start the browser with $capabilities
// A) When using RemoteWebDriver::create()
$driver = RemoteWebDriver::create($serverUrl, $capabilities);
// B) When using FirefoxDriver::start to start local Geckodriver
$driver = FirefoxDriver::start($capabilities);

See php-webdriver wiki article for more Firefox examples.

Upvotes: 7

RobH
RobH

Reputation: 1639

Found this in the php-webdriver docs:

use Facebook\WebDriver\Remote\DesiredCapabilities;

$desiredCapabilities = DesiredCapabilities::firefox();
    .
    .
    .
// Run headless firefox
$desiredCapabilities->setCapability('moz:firefoxOptions', ['args' => ['-headless']]);

$driver = RemoteWebDriver::create($host, $desiredCapabilities);

Upvotes: 0

Related Questions