Skip to content

Commit

Permalink
Merge pull request #27 from aik099/session-reset-with-initial-window-…
Browse files Browse the repository at this point in the history
…rename-fix

Harden window closing code upon session reset
  • Loading branch information
aik099 authored Jun 28, 2024
2 parents 71c242b + d04dfda commit 73ad0b6
Showing 1 changed file with 17 additions and 17 deletions.
34 changes: 17 additions & 17 deletions src/WebdriverClassicDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class WebdriverClassicDriver extends CoreDriver

private string $webDriverHost;

private ?string $initialWindowName = null;
private ?string $initialWindowHandle = null;

/**
* @param string $browserName One of 'edge', 'firefox', 'chrome' or any one of {@see WebDriverBrowserType} constants.
Expand All @@ -104,7 +104,7 @@ public function start(): void
try {
$this->webDriver = RemoteWebDriver::create($this->webDriverHost, $this->desiredCapabilities);
$this->applyTimeouts();
$this->initialWindowName = $this->getWindowName();
$this->initialWindowHandle = $this->getWebDriver()->getWindowHandle();
} catch (\Throwable $e) {
throw new DriverException("Could not start driver: {$e->getMessage()}", 0, $e);
}
Expand Down Expand Up @@ -136,16 +136,20 @@ public function stop(): void
*/
public function reset(): void
{
// switch to default window..
$this->switchToWindow();
// ..and close all other windows
foreach ($this->getWindowNames() as $name) {
if ($name !== $this->initialWindowName) {
$this->withWindow($name, fn() => $this->getWebDriver()->close());
$webDriver = $this->getWebDriver();

// Close all windows except the initial one.
foreach ($webDriver->getWindowHandles() as $windowHandle) {
if ($windowHandle === $this->initialWindowHandle) {
continue;
}

$webDriver->switchTo()->window($windowHandle);
$webDriver->close();
}

$this->getWebDriver()->manage()->deleteAllCookies();
$this->switchToWindow();
$webDriver->manage()->deleteAllCookies();
}

public function visit(string $url): void
Expand Down Expand Up @@ -175,15 +179,11 @@ public function back(): void

public function switchToWindow(?string $name = null): void
{
if ($name === null) {
$name = $this->initialWindowName;
}

if (is_string($name)) {
$name = $this->getWindowHandleFromName($name);
}
$handle = $name === null
? $this->initialWindowHandle
: $this->getWindowHandleFromName($name);

$this->getWebDriver()->switchTo()->window((string)$name);
$this->getWebDriver()->switchTo()->window((string)$handle);
}

public function switchToIFrame(?string $name = null): void
Expand Down

0 comments on commit 73ad0b6

Please sign in to comment.