Skip to content

Commit

Permalink
Port window handling implementation from another driver
Browse files Browse the repository at this point in the history
  • Loading branch information
aik099 committed Feb 24, 2024
1 parent 4ca4083 commit 716ac2a
Showing 1 changed file with 60 additions and 3 deletions.
63 changes: 60 additions & 3 deletions src/Selenium2Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
*/
class Selenium2Driver extends CoreDriver
{
private const W3C_WINDOW_HANDLE_PREFIX = 'w3cwh:';

/**
* Whether the browser has been started
* @var bool
Expand Down Expand Up @@ -425,7 +427,45 @@ public function back()

public function switchToWindow(?string $name = null)
{
$this->getWebDriverSession()->focusWindow($name ?: '');
if ($name === null) {
$windowHandles = $this->getWebDriverSession()->window_handles();
$name = self::W3C_WINDOW_HANDLE_PREFIX . reset($windowHandles);
}

if (is_string($name)) {
$name = $this->getWindowHandleFromName($name);
}

$this->getWebDriverSession()->focusWindow($name);
}

/**
* @throws DriverException
*/
private function getWindowHandleFromName(string $name): string
{
// if name is actually prefixed window handle, just remove the prefix
if (strpos($name, self::W3C_WINDOW_HANDLE_PREFIX) === 0) {
return substr($name, strlen(self::W3C_WINDOW_HANDLE_PREFIX));
}

// ..otherwise check if any existing window has the specified name

$origWindowHandle = $this->getWebDriverSession()->window_handle();

try {
foreach ($this->getWebDriverSession()->window_handles() as $handle) {
$this->getWebDriverSession()->focusWindow($handle);

if ($this->evaluateScript('window.name') === $name) {
return $handle;
}
}

throw new DriverException("Could not find handle of window named \"$name\"");

Check warning on line 465 in src/Selenium2Driver.php

View check run for this annotation

Codecov / codecov/patch

src/Selenium2Driver.php#L465

Added line #L465 was not covered by tests
} finally {
$this->getWebDriverSession()->focusWindow($origWindowHandle);
}
}

public function switchToIFrame(?string $name = null)
Expand Down Expand Up @@ -492,12 +532,29 @@ public function getScreenshot()

public function getWindowNames()
{
return $this->getWebDriverSession()->window_handles();
$origWindow = $this->getWebDriverSession()->window_handle();

try {
$result = array();
foreach ($this->getWebDriverSession()->window_handles() as $tempWindow) {
$this->getWebDriverSession()->focusWindow($tempWindow);
$result[] = $this->getWindowName();
}
return $result;
} finally {
$this->getWebDriverSession()->focusWindow($origWindow);
}
}

public function getWindowName()
{
return $this->getWebDriverSession()->window_handle();
$name = (string) $this->evaluateScript('window.name');

if ($name === '') {
$name = self::W3C_WINDOW_HANDLE_PREFIX . $this->getWebDriverSession()->window_handle();
}

return $name;
}

/**
Expand Down

0 comments on commit 716ac2a

Please sign in to comment.