Execute javascript in Selenium with Facebook PHP WebDriver

MattRogowski picture MattRogowski · Jul 29, 2016 · Viewed 8.3k times · Source

I am trying to follow this documentation to execute a script, and all I am getting is an error saying the executeScript method is undefined.

$this->driver->navigateTo('/');
$this->driver->clickElement('#member_opt_in + label');
$this->driver->executeScript("alert('Hi');");

The documentation uses $session, and says higher up the page that this is shorthand, but doesn't explain anywhere at all what $session actually contains or how to assign it.

Answer

Ondrej Machulda picture Ondrej Machulda · Aug 5, 2016

The wiki on GitHub is not up-to-date with the current php-webdriver library and refers to previous (pre 2013) version of it - but the library was rewritten from scratch since.

To execute Selenium commands you need instance of RemoteWebDriver. An example can be seen in readme.

With RemoteWebDriver instance in $driver variable you can execute:

$driver->get('http://google.com');

$element = $driver->findElement(WebDriverBy::cssSelector('#member_opt_in + label'));
$elemen->click();

// Execute javascript:
$driver->executeScript('alert("Hi");');
// Or to execute the javascript as non-blocking, ie. asynchronously:
$driver->executeAsyncScript('alert("Hi");');

Refer to API documentation for more information.