-
Notifications
You must be signed in to change notification settings - Fork 0
Alert, Window Tab, frame iframe and active element
The guide talks about how to switch between different alert, windows and frame.
For more details, read WebDriverAlert.
$this->driver->wait()->until(
WebDriverExpectedCondition::alertIsPresent(),
'I am expecting an alert!',
);
// accepting the alert
$driver->switchTo()->alert()->accept();
// cancel/dismiss the alert
$driver->switchTo()->alert()->dismiss();
// get the text on the alert
$message = $driver->switchTo()->alert()->getText();
// send keys to the alert
$driver->switchTo()->alert()->sendKeys($name);
When you click a link or a button, a new window, tab or popup might appear and you need to switch to that window to fill a form or grant the permission, etc....
<a href='/new_window.php' target='_blank'>
Each window has an unique window handle, a string for WebDriver to identify the window and switch between them.
$current_handle = $driver->getWindowHandle();
// Get all window handles available to the current webdriver session.
// This will returns an array of string
$handles = $driver->getWindowHandles();
If you want to change the focus to the new window opened, switch to the last window opened by
$driver->switchTo()->window(
end($driver->getWindowHandles())
);
// using the browser shortcut to create a new tab
$driver->getKeyboard()->sendKeys(
array(WebDriverKeys::CONTROL, 't'),
);
// using the browser shortcut to create a new window
$driver->getKeyboard()->sendKeys(
array(WebDriverKeys::CONTROL, 'n'),
);
In order to interact with elements inside a frame or iframe, switch to that frame first!
$my_frame could be either
- a
string, the name or id of the frame element, or
$my_frame = 'id_or_name';
$driver->switchTo()->frame($my_frame);
- a
WebDriverElement, the iframe element found by$driver->findElement($by).
$my_frame = $driver->findElement(WebDriverBy::id('my_frame'));
$driver->switchTo()->frame($my_frame);
$driver->switchTo()->defaultContent();
Switches to the element that currently has focus within the document currently "switched to", or the body element if this cannot be detected. This matches the semantics of calling document.activeElement in Javascript.
$active_element = $driver->switchTo()->activeElement();
WebDriverTargetLocator manages the focus of WebDriver. Read the source code if you want to know more.