98 lines
2.5 KiB
Java
98 lines
2.5 KiB
Java
package webelements;
|
|
|
|
import java.util.Set;
|
|
|
|
import org.openqa.selenium.By;
|
|
import org.openqa.selenium.WebDriver;
|
|
import org.openqa.selenium.WebElement;
|
|
import org.openqa.selenium.firefox.FirefoxDriver;
|
|
|
|
public class FramesAndWindows
|
|
{
|
|
private static void sleep(long milliseconds)
|
|
{
|
|
try
|
|
{
|
|
Thread.sleep(milliseconds);
|
|
}
|
|
catch (InterruptedException e)
|
|
{
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args)
|
|
{
|
|
// Specify path to WebDriver:
|
|
System.setProperty("webdriver.gecko.driver", "/snap/bin/geckodriver");
|
|
|
|
// Launch browser and navigate to test page:
|
|
WebDriver driver = new FirefoxDriver();
|
|
driver.manage().window().maximize();
|
|
driver.get("https://ramoncaballero.dev/sdet/selenium-webdriver/playgrounds/");
|
|
|
|
// Click on the 'Frames and Windows' accordion item:
|
|
driver.findElement(By.xpath("//button[contains(text(),'Frames and Windows')]")).click();
|
|
|
|
//
|
|
// FRAMES
|
|
//
|
|
|
|
// Switch to the iframe:
|
|
WebElement frame = driver.findElement(By.id("custom-iframe"));
|
|
driver.switchTo().frame(frame);
|
|
|
|
// Perform the actions we need to do:
|
|
driver.findElement(By.id("frame-button")).click();
|
|
|
|
// Switch back to the default document:
|
|
driver.switchTo().defaultContent();
|
|
|
|
//
|
|
// WINDOWS
|
|
//
|
|
|
|
// Get the handle (or identifier) of the original window:
|
|
String originalWindowHandle = driver.getWindowHandle();
|
|
|
|
// Click the button that opens a new window:
|
|
driver.findElement(By.id("new-window-button")).click();
|
|
|
|
// Most likely the new window won't finish loading its content before its title is queried by the
|
|
// driver, so we sleep the execution a little bit to give it enough time:
|
|
sleep(500);
|
|
|
|
// Get the handles of all the windows (i.e. handle of the original window + handle of the new window):
|
|
Set<String> windowHandles = driver.getWindowHandles();
|
|
|
|
// Figure out the handle of the new window:
|
|
String newWindowHandle = "";
|
|
|
|
for (String windowHandle : windowHandles)
|
|
{
|
|
if (!originalWindowHandle.contentEquals(windowHandle))
|
|
{
|
|
newWindowHandle = windowHandle;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Switch to the new window:
|
|
driver.switchTo().window(newWindowHandle);
|
|
|
|
// Perform the actions we need to do:
|
|
System.out.println("The title of the new window is: " + driver.getTitle());
|
|
|
|
// Close the window:
|
|
driver.close();
|
|
|
|
// Switch back to the default document:
|
|
driver.switchTo().window(originalWindowHandle);
|
|
|
|
//
|
|
|
|
// This is commented out so you can actually see what happened in the web page:
|
|
// driver.quit();
|
|
}
|
|
}
|