Skip to content

Alert, Window Tab, frame iframe and active element

Wai Hon Law edited this page Jan 5, 2015 · 4 revisions

The guide talks about how to switch between different alert, windows and frame.

Alert

For more details, read WebDriverAlert.

Waiting for the alert

$this->driver->wait()->until(
  WebDriverExpectedCondition::alertIsPresent(),
  'I am expecting an alert!',
);

Accepting an alert

// accepting the alert
$driver->switchTo()->alert()->accept();

Cancel an alert

// cancel/dismiss the alert
$driver->switchTo()->alert()->dismiss();

Get the message on the alert

// get the text on the alert
$message = $driver->switchTo()->alert()->getText();

Answering question on the alert

// send keys to the alert
$driver->switchTo()->alert()->sendKeys($name);

Window, Tab

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.

Get the current window handle

$current_handle = $driver->getWindowHandle();

Get all window handles

// Get all window handles available to the current webdriver session.
// This will returns an array of string
$handles = $driver->getWindowHandles();

Switch to the new window

If you want to change the focus to the new window opened, switch to the last window opened by

$driver->switchTo()->window(
  nullthrows(last($this->driver->getWindowHandles()))
);

Frame, iframe

In order to interact with elements inside a frame or iframe, switch to that frame first!

Switching to another frame or iframe

$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);

Switching back to the main frame on the page

$driver->switchTo()->defaultContent();

Get the active element

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();

Reference

WebDriverTargetLocator manages the focus of WebDriver. Read the source code if you want to know more.

Clone this wiki locally