2

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.

Ajanth
  • 2,435
  • 3
  • 20
  • 23
MattRogowski
  • 726
  • 2
  • 7
  • 22

2 Answers2

4

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.

Ondrej Machulda
  • 998
  • 1
  • 12
  • 24
  • which version is needed? – Andrew Vakhniuk Jun 06 '18 at 14:44
  • @AndrewVakhniuk Well any 1.0.0+, but why don't you try ty latest one - 1.6.0. – Ondrej Machulda Jun 07 '18 at 15:26
  • Excellent explanation Ondrej and I followed some of your comments on github as well, do you think we can use the executeAsyncScript to figure out if Ajax stopped loading? I'm trying to figure this out via https://stackoverflow.com/questions/64590437/php-webdriver-wait-for-ajax-to-finish-executing – Robert Sinclair Nov 03 '20 at 13:05
1

For people using Laravel Dusk (and in my case I wanted to click a Facebook modal to test a federated login via Socialite):

use Facebook\WebDriver\WebDriverBy;

$confirmationButton = $browser->driver->findElement(WebDriverBy::cssSelector('.layerConfirm')); 
$browser->driver->executeScript("arguments[0].click();", [$confirmationButton]);

This seemed to force the click even though previously screenshots from Dusk were showing that a dark (mostly black) translucent layer was hovering over the whole screen, preventing any clicks (even though in normal non-Dusk attempts, everything in the browser looked fine).

See also:

P.S. I also later realized that the Facebook modal had a fancy gradual transition when it was inflating / appearing, so it seems that $browser->waitFor('.layerConfirm', 4) was firing prematurely, so I thought I could instead just use pause(2000) to force it to wait a full 2 seconds for the transition to complete (and then wouldn't need to use executeScript at all). But no amount of pause let the modal become fully visible and clickable.

Ryan
  • 22,332
  • 31
  • 176
  • 357