Selenium Advanced Topics
Alerts, iFrames, JavaScript, File Upload/Download
Handling Alerts & Popups
JavaScript alerts, confirmations, and prompts require special handling. WebDriver provides the Alert interface to interact with these dialogs.
Simple Alert
// Switch to alert
Alert alert = driver.switchTo().alert();
// Get alert text
String alertText = alert.getText();
System.out.println(alertText);
// Accept alert
alert.accept();
Confirmation Dialog
// Handle confirm dialog
Alert confirmAlert = driver.switchTo().alert();
// Click Cancel
confirmAlert.dismiss();
// OR Click OK
confirmAlert.accept();
Prompt Dialog
// Handle prompt
Alert promptAlert = driver.switchTo().alert();
// Type text in prompt
promptAlert.sendKeys("John Doe");
// Submit
promptAlert.accept();
Wait for Alert
import org.openqa.selenium.support.ui.ExpectedConditions;
// Wait for alert to appear
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
Working with Frames & iFrames
Frames and iFrames are separate HTML documents within a page. WebDriver needs to switch context to interact with elements inside frames.
Switch to Frame by Index
// Switch to first frame (index 0)
driver.switchTo().frame(0);
// Interact with elements inside frame
driver.findElement(By.id("username")).sendKeys("admin");
Switch to Frame by Name/ID
// Switch by name attribute
driver.switchTo().frame("frameName");
// Switch by id attribute
driver.switchTo().frame("frameId");
Switch to Frame by WebElement
// Find frame element first
WebElement frameElement = driver.findElement(By.cssSelector("iframe.content-frame"));
// Switch to frame using WebElement
driver.switchTo().frame(frameElement);
// Perform actions inside frame
driver.findElement(By.id("button")).click();
Nested Frames
// Switch to parent frame
driver.switchTo().frame("parentFrame");
// Switch to child frame inside parent
driver.switchTo().frame("childFrame");
// Interact with nested frame content
driver.findElement(By.id("submit")).click();
Switch Back to Main Content
// Switch to default content (main page)
driver.switchTo().defaultContent();
// Switch to parent frame (one level up)
driver.switchTo().parentFrame();
Frame Switching Best Practices
- Always switch back to default content after frame operations
- Use
parentFrame()to go one level up in nested frames - Wait for frame to load before switching to it
- Prefer switching by WebElement over index for stability
JavaScript Executor
JavaScriptExecutor allows you to execute JavaScript code directly in the browser. Useful for handling complex scenarios that WebDriver can’t handle natively.
Basic Setup
import org.openqa.selenium.JavascriptExecutor;
// Cast WebDriver to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
Click Hidden Element
// Click element not visible or not clickable
WebElement element = driver.findElement(By.id("hiddenButton"));
js.executeScript("arguments[0].click();", element);
Scroll Operations
// Scroll to bottom of page
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
// Scroll to top
js.executeScript("window.scrollTo(0, 0);");
// Scroll to specific element
WebElement element = driver.findElement(By.id("section5"));
js.executeScript("arguments[0].scrollIntoView(true);", element);
// Scroll by pixel amount
js.executeScript("window.scrollBy(0, 500);");
Modify Element Properties
// Change element attribute
WebElement inputField = driver.findElement(By.id("email"));
js.executeScript("arguments[0].setAttribute('value', 'test@example.com');", inputField);
// Remove attribute
js.executeScript("arguments[0].removeAttribute('disabled');", element);
// Change CSS style
js.executeScript("arguments[0].style.border='3px solid red';", element);
Get Page Information
// Get page title
String title = (String) js.executeScript("return document.title;");
// Get page URL
String url = (String) js.executeScript("return document.URL;");
// Get page height
Long height = (Long) js.executeScript("return document.body.scrollHeight;");
// Get inner text
String text = (String) js.executeScript("return arguments[0].innerText;", element);
Generate Alerts
// Create custom alert
js.executeScript("alert('This is a custom alert!');");
Handle Calendar/Date Picker
// Set date directly bypassing calendar UI
WebElement datePicker = driver.findElement(By.id("dateInput"));
js.executeScript("arguments[0].value='2024-12-31';", datePicker);
Taking Screenshots
Screenshots are essential for test reporting and debugging. Selenium provides multiple ways to capture screenshots at different levels.
Full Page Screenshot
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
import java.io.File;
// Capture full page screenshot
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
File destination = new File("./screenshots/fullpage.png");
FileUtils.copyFile(source, destination);
Element Screenshot (Selenium 4)
// Capture specific element
WebElement element = driver.findElement(By.id("logo"));
File elementScreenshot = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementScreenshot, new File("./screenshots/element.png"));
Screenshot with Timestamp
import java.text.SimpleDateFormat;
import java.util.Date;
// Create screenshot with timestamp
String timestamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
String fileName = "screenshot_" + timestamp + ".png";
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("./screenshots/" + fileName));
Screenshot as Base64 String
// Get screenshot as base64 (useful for reports)
String base64Screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.BASE64);
// Use in HTML reports
String imgTag = "<img src='data:image/png;base64," + base64Screenshot + "'/>";
Screenshot on Test Failure
public void captureScreenshotOnFailure(String testName) {
try {
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String filePath = "./screenshots/failed_" + testName + ".png";
FileUtils.copyFile(screenshot, new File(filePath));
System.out.println("Screenshot saved: " + filePath);
} catch (Exception e) {
System.out.println("Failed to capture screenshot: " + e.getMessage());
}
}
Screenshot Best Practices
- Always create screenshots directory before saving files
- Use timestamps or test names to avoid overwriting
- Capture screenshots on test failures for debugging
- Consider element screenshots for faster performance
- Use Base64 format for embedding in HTML reports
File Upload & Download
File handling is a common requirement in web automation. Learn how to upload files and verify downloads.
File Upload (Direct)
// Upload file using sendKeys (for input type="file")
WebElement uploadElement = driver.findElement(By.id("fileUpload"));
// Provide absolute path to file
String filePath = System.getProperty("user.dir") + "/testdata/sample.pdf";
uploadElement.sendKeys(filePath);
// Click submit/upload button
driver.findElement(By.id("submitBtn")).click();
File Upload (Using Robot Class)
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
// Click upload button to open file dialog
driver.findElement(By.id("uploadBtn")).click();
// Copy file path to clipboard
StringSelection filePath = new StringSelection("C:\\testdata\\file.pdf");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filePath, null);
// Paste and press Enter using Robot
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Configure Download Directory
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.HashMap;
// Set download directory for Chrome
String downloadPath = System.getProperty("user.dir") + "/downloads";
HashMap<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", downloadPath);
prefs.put("download.prompt_for_download", false);
prefs.put("plugins.always_open_pdf_externally", true);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
Verify Downloaded File
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public boolean isFileDownloaded(String fileName, int timeoutSeconds) {
String downloadPath = System.getProperty("user.dir") + "/downloads";
Path filePath = Paths.get(downloadPath, fileName);
int waited = 0;
while (waited < timeoutSeconds) {
if (Files.exists(filePath)) {
return true;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
waited++;
}
return false;
}
Managing Cookies
Cookies store session data and user preferences. WebDriver provides methods to manage browser cookies programmatically.
Get All Cookies
import org.openqa.selenium.Cookie;
// Get all cookies
Set<Cookie> cookies = driver.manage().getCookies();
// Print all cookies
for (Cookie cookie : cookies) {
System.out.println("Name: " + cookie.getName());
System.out.println("Value: " + cookie.getValue());
System.out.println("Domain: " + cookie.getDomain());
System.out.println("Path: " + cookie.getPath());
System.out.println("---");
}
Get Specific Cookie
// Get cookie by name
Cookie sessionCookie = driver.manage().getCookieNamed("sessionId");
if (sessionCookie != null) {
System.out.println("Session ID: " + sessionCookie.getValue());
}
Add Cookie
// Create and add new cookie
Cookie newCookie = new Cookie("username", "testuser");
driver.manage().addCookie(newCookie);
// Add cookie with more options
Cookie customCookie = new Cookie.Builder("token", "abc123xyz")
.domain("example.com")
.path("/")
.isSecure(true)
.isHttpOnly(true)
.build();
driver.manage().addCookie(customCookie);
Delete Cookies
// Delete specific cookie
driver.manage().deleteCookieNamed("sessionId");
// Delete cookie object
Cookie cookie = driver.manage().getCookieNamed("username");
driver.manage().deleteCookie(cookie);
// Delete all cookies
driver.manage().deleteAllCookies();
Save and Load Cookies
import java.io.*;
// Save cookies to file
public void saveCookies(String filePath) {
try (FileWriter file = new FileWriter(filePath)) {
for (Cookie cookie : driver.manage().getCookies()) {
file.write(cookie.getName() + ";" + cookie.getValue() + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Load cookies from file
public void loadCookies(String filePath) {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(";");
Cookie cookie = new Cookie(parts[0], parts[1]);
driver.manage().addCookie(cookie);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Cookie Use Cases
- Skip login by injecting authentication cookies
- Test session management and timeouts
- Save user preferences across test runs
- Verify cookie security attributes (HttpOnly, Secure)
- Test GDPR cookie consent flows
Browser Options & Capabilities
Customize browser behavior with options and capabilities for different browsers.
Chrome Options
import org.openqa.selenium.chrome.ChromeOptions;
ChromeOptions options = new ChromeOptions();
// Add arguments
options.addArguments("--start-maximized");
options.addArguments("--disable-notifications");
options.addArguments("--disable-popup-blocking");
options.addArguments("--incognito");
// Headless mode
options.addArguments("--headless=new");
// Disable automation flags
options.setExperimentalOption("excludeSwitches",
Arrays.asList("enable-automation"));
// Set user agent
options.addArguments("user-agent=Mozilla/5.0 Custom Agent");
WebDriver driver = new ChromeDriver(options);
Firefox Options
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
FirefoxOptions options = new FirefoxOptions();
// Add arguments
options.addArguments("--headless");
options.addArguments("--width=1920");
options.addArguments("--height=1080");
// Set Firefox profile preferences
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/pdf");
options.setProfile(profile);
WebDriver driver = new FirefoxDriver(options);
Edge Options
import org.openqa.selenium.edge.EdgeOptions;
EdgeOptions options = new EdgeOptions();
// Add arguments (similar to Chrome)
options.addArguments("--start-maximized");
options.addArguments("--inprivate");
options.addArguments("--disable-extensions");
WebDriver driver = new EdgeDriver(options);
Common Chrome Arguments
// Performance & Testing
--start-maximized
--disable-extensions
--disable-gpu
--no-sandbox
--disable-dev-shm-usage
// Privacy & Security
--incognito
--disable-notifications
--disable-popup-blocking
--disable-blink-features=AutomationControlled
// Window Size
--window-size=1920,1080
--headless=new
Mobile Emulation
import java.util.HashMap;
// Emulate mobile device
Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "iPhone 12 Pro");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("mobileEmulation", mobileEmulation);
WebDriver driver = new ChromeDriver(options);
Advanced User Actions
The Actions class enables complex user interactions like mouse hover, drag-and-drop, keyboard combinations, and more.
Mouse Hover
import org.openqa.selenium.interactions.Actions;
Actions actions = new Actions(driver);
// Hover over element
WebElement menu = driver.findElement(By.id("mainMenu"));
actions.moveToElement(menu).perform();
// Hover and click submenu
WebElement submenu = driver.findElement(By.id("submenu"));
actions.moveToElement(menu)
.moveToElement(submenu)
.click()
.perform();
Drag and Drop
// Drag and drop element
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
actions.dragAndDrop(source, target).perform();
// Drag by offset
actions.dragAndDropBy(source, 100, 200).perform();
Right Click & Double Click
// Right click (context menu)
WebElement element = driver.findElement(By.id("rightClickArea"));
actions.contextClick(element).perform();
// Double click
WebElement button = driver.findElement(By.id("doubleClickBtn"));
actions.doubleClick(button).perform();
Keyboard Actions
import org.openqa.selenium.Keys;
// Send keyboard shortcuts
actions.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
// Copy and paste
WebElement source = driver.findElement(By.id("source"));
WebElement target = driver.findElement(By.id("target"));
source.click();
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
actions.keyDown(Keys.CONTROL).sendKeys("c").keyUp(Keys.CONTROL).perform();
target.click();
actions.keyDown(Keys.CONTROL).sendKeys("v").keyUp(Keys.CONTROL).perform();
Click and Hold
// Click and hold element
WebElement slider = driver.findElement(By.id("slider"));
actions.clickAndHold(slider)
.moveByOffset(100, 0)
.release()
.perform();
Scroll to Element
// Scroll to element (Selenium 4)
WebElement element = driver.findElement(By.id("footer"));
actions.scrollToElement(element).perform();
// Scroll by amount
actions.scrollByAmount(0, 500).perform();
Actions Best Practices
- Always call
perform()to execute the action chain - Chain multiple actions for complex interactions
- Use
pause()between actions if needed - Combine with explicit waits for reliable execution
Window & Tab Management
Handle multiple browser windows and tabs effectively during automation.
Get Window Handles
// Get current window handle
String mainWindow = driver.getWindowHandle();
System.out.println("Main window: " + mainWindow);
// Get all window handles
Set<String> allWindows = driver.getWindowHandles();
System.out.println("Total windows: " + allWindows.size());
Switch Between Windows
// Store main window
String mainWindow = driver.getWindowHandle();
// Click link that opens new window
driver.findElement(By.linkText("Open New Window")).click();
// Switch to new window
for (String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(mainWindow)) {
driver.switchTo().window(windowHandle);
break;
}
}
// Perform actions in new window
System.out.println("New window title: " + driver.getTitle());
// Close current window
driver.close();
// Switch back to main window
driver.switchTo().window(mainWindow);
Open New Tab (Selenium 4)
// Open new tab
driver.switchTo().newWindow(WindowType.TAB);
// Open new window
driver.switchTo().newWindow(WindowType.WINDOW);
// Navigate in new tab
driver.get("https://example.com");
Manage Window Size & Position
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
// Maximize window
driver.manage().window().maximize();
// Fullscreen mode
driver.manage().window().fullscreen();
// Set window size
Dimension size = new Dimension(1024, 768);
driver.manage().window().setSize(size);
// Set window position
Point position = new Point(100, 100);
driver.manage().window().setPosition(position);
// Get current window size
Dimension currentSize = driver.manage().window().getSize();
System.out.println("Width: " + currentSize.getWidth());
System.out.println("Height: " + currentSize.getHeight());
Handle Multiple Tabs
// Store all window handles in ArrayList
ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
// Switch to first tab
driver.switchTo().window(tabs.get(0));
// Switch to second tab
driver.switchTo().window(tabs.get(1));
// Close all except main tab
String mainTab = tabs.get(0);
for (String tab : tabs) {
if (!tab.equals(mainTab)) {
driver.switchTo().window(tab);
driver.close();
}
}
driver.switchTo().window(mainTab);
Next Steps
Continue Learning
- Integrate with TestNG/JUnit for structured test execution
- Implement Page Object Model (POM) design pattern
- Set up data-driven testing with external data sources
- Configure Selenium Grid for parallel test execution
- Add comprehensive reporting with Extent Reports
- Integrate with CI/CD pipelines (Jenkins, GitHub Actions)