Execute javascript in Selenium with Facebook PHP WebDriver

◇◆丶佛笑我妖孽 提交于 2019-12-11 06:56:23

问题


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.


回答1:


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.




回答2:


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:

  • https://stackoverflow.com/a/11956130/470749
  • https://facebook.github.io/php-webdriver/1.3.0/Facebook/WebDriver/JavaScriptExecutor.html

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.



来源:https://stackoverflow.com/questions/38662087/execute-javascript-in-selenium-with-facebook-php-webdriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!