DEV Community

Cover image for Selenium Java: Handle Alerts & Popups, IFrames, Switch Windows
Anne Quinkenstein
Anne Quinkenstein

Posted on • Updated on

Selenium Java: Handle Alerts & Popups, IFrames, Switch Windows

Handle JavaScript alert and popup

Use the Alert interface method to switch to the alert box

Alert alert = driver.switchTo().alert();
alert.getText();
//ok
driver.switchTo().alert().accept();  
//cancel
driver.switchTo().alert().dismiss();  
Enter fullscreen mode Exit fullscreen mode

Handle IFrames

IFrames are the HTML document embed on top of another HTML document. <iframe>...</iframe>
Switch to the Frame by Web Element:

  Actions action = new Actions(driver);
 WebElement frameTop = driver.findElement(By.xpath("//frame[@name='frame-top']"));
 driver.switchTo().frame(frameTop);
Enter fullscreen mode Exit fullscreen mode
driver.switchTo().frame(index)
driver.switchTo().frame(Id)
driver.switchTo().frame(Name)
driver.switchTo().frame(WebElement) 
Enter fullscreen mode Exit fullscreen mode

Switch to new Window

        Set <String> windows = driver.getWindowHandles();
        Iterator <String> it = windows.iterator();
        String parentId = it.next();
        String childId = it.next();
        driver.switchTo().window(childId);
        driver.switchTo().window(parentId);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)