diff --git a/src/Client.php b/src/Client.php index 3d3af325..9a4cca97 100644 --- a/src/Client.php +++ b/src/Client.php @@ -15,6 +15,7 @@ use Facebook\WebDriver\Exception\NoSuchElementException; use Facebook\WebDriver\Exception\TimeOutException; +use Facebook\WebDriver\JavaScriptExecutor; use Facebook\WebDriver\Remote\RemoteWebElement; use Facebook\WebDriver\WebDriver; use Facebook\WebDriver\WebDriverBy; @@ -38,7 +39,7 @@ * * @method Crawler getCrawler() */ -final class Client extends BaseClient implements WebDriver +final class Client extends BaseClient implements WebDriver, JavaScriptExecutor { use ExceptionThrower; @@ -389,4 +390,22 @@ public function findElements(WebDriverBy $locator) return $this->webDriver->findElements($locator); } + + public function executeScript($script, array $arguments = []) + { + if (!$this->webDriver instanceof JavaScriptExecutor) { + throw new \RuntimeException(sprintf('"%s" does not implement "%s".', \get_class($this->webDriver), JavaScriptExecutor::class)); + } + + return $this->webDriver->executeScript($script, $arguments); + } + + public function executeAsyncScript($script, array $arguments = []) + { + if (!$this->webDriver instanceof JavaScriptExecutor) { + throw new \RuntimeException(sprintf('"%s" does not implement "%s".', \get_class($this->webDriver), JavaScriptExecutor::class)); + } + + return $this->webDriver->executeAsyncScript($script, $arguments); + } } diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 7d287ab0..891b7c41 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -13,6 +13,7 @@ namespace Symfony\Component\Panther\Tests; +use Facebook\WebDriver\JavaScriptExecutor; use Facebook\WebDriver\Remote\RemoteWebElement; use Facebook\WebDriver\WebDriver; use Facebook\WebDriver\WebDriverExpectedCondition; @@ -35,6 +36,7 @@ public function testCreateClient() $client = self::createPantherClient(); $this->assertInstanceOf(BrowserKitClient::class, $client); $this->assertInstanceOf(WebDriver::class, $client); + $this->assertInstanceOf(JavaScriptExecutor::class, $client); $this->assertInstanceOf(KernelInterface::class, self::$kernel); } @@ -47,6 +49,30 @@ public function testWaitFor() $this->assertSame('Hello', $crawler->filter('#hello')->text()); } + public function testExecuteScript() + { + $client = self::createPantherClient(); + $client->request('GET', '/basic.html'); + $innerText = $client->executeScript('return document.querySelector(arguments[0]).innerText;', ['.p-1']); + $this->assertSame('P1', $innerText); + } + + public function testExecuteAsyncScript() + { + $client = self::createPantherClient(); + $client->request('GET', '/basic.html'); + $innerText = $client->executeAsyncScript(<<assertSame('P1', $innerText); + } + /** * @dataProvider clientFactoryProvider */