3 namespace Zumba\Mink\Driver;
5 use Behat\Mink\Exception\DriverException;
8 * Class JavascriptTrait
9 * @package Zumba\Mink\Driver
11 trait JavascriptTrait {
14 * Executes a script on the browser
15 * @param string $script
17 public function executeScript($script) {
18 $this->browser->execute($this->fixSelfExecutingFunction($script));
22 * Evaluates a script and returns the result
23 * @param string $script
26 public function evaluateScript($script) {
27 $script = preg_replace('/^return\s+/', '', $script);
29 $script = $this->fixSelfExecutingFunction($script);
31 return $this->browser->evaluate($script);
35 * Waits some time or until JS condition turns true.
37 * @param integer $timeout timeout in milliseconds
38 * @param string $condition JS condition
40 * @throws DriverException When the operation cannot be done
42 public function wait($timeout, $condition) {
43 $start = microtime(true);
44 $end = $start + $timeout / 1000.0;
46 $result = $this->browser->evaluate($condition);
48 // No need to wait any longer when the condition is met already.
52 } while (microtime(true) < $end && !$result);
58 * Fixes self-executing functions to allow evaluating them.
60 * The self-executing function must be wrapped in braces to work.
62 * @param string $script
66 private function fixSelfExecutingFunction($script)
68 if (preg_match('/^function[\s\(]/', $script)) {
69 $script = preg_replace('/;$/', '', $script);
70 $script = '(' . $script . ')';