πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Selenium 4 Commands
Java WebDriver

Selenium 100+ Commands
Advanced & Framework Level

A clean, interactive, production-ready reference catalog. Pierce Shadow DOMs, handle relative locators, configure multi-thread parallel runners, manage session cookies, and automate dynamic iframe overlays with Selenium 4 standards.

Level:
🎯

Complete Selenium Preparation Track

Combine these 100+ raw commands with our interactive **Scenario-Based Interview Questions Hub** to review detailed senior-level analysis and STAR method responses!

Browser Control

Launch Chrome Browser

Core

Instantiates a new ChromeDriver instance to launch a native Google Chrome browser session. Selenium 4 automatically resolves the matching driver executable using Selenium Manager.

WebDriver driver = new ChromeDriver();
πŸ’‘

Pro-Tip: System.setProperty() setup is completely obsolete in Selenium 4! Let Selenium Manager handle binary matching.

ID: #1
Browser Control

Launch Firefox Browser

Core

Instantiates a new FirefoxDriver instance using the native Geckodriver protocol to launch a Mozilla Firefox browser session.

WebDriver driver = new FirefoxDriver();
ID: #2
Browser Control

Launch Edge Browser

Core

Instantiates a new EdgeDriver instance to control a Chromium-based Microsoft Edge browser session.

WebDriver driver = new EdgeDriver();
ID: #3
Browser Control

Open Web Page (Get)

Core

Loads a webpage in the current browser window. This method blocks the execution thread until the page has fully loaded according to the configured PageLoadStrategy.

driver.get("https://careerraah.com");
πŸ’‘

Pro-Tip: Always use absolute URLs containing valid http:// or https:// protocols.

ID: #4
Browser Control

Navigate to URL

Core

Navigates to the specified URL. Behaves identically to driver.get() but maintains full browser history, enabling backwards and forwards navigation.

driver.navigate().to("https://careerraah.com/dashboard");
ID: #5
Browser Control

Navigate Backwards

Core

Simulates clicking the browser's native 'Back' button in history.

driver.navigate().back();
ID: #6
Browser Control

Navigate Forwards

Core

Simulates clicking the browser's native 'Forward' button in history.

driver.navigate().forward();
ID: #7
Browser Control

Refresh Page

Core

Reloads the current active document in the browser window.

driver.navigate().refresh();
ID: #8
Browser Control

Get Page Title

Core

Retrieves the document title of the active webpage.

String title = driver.getTitle();
ID: #9
Browser Control

Get Current URL

Core

Retrieves the complete, absolute URL string of the webpage currently active in the viewport.

String currentUrl = driver.getCurrentUrl();
ID: #10
Browser Control

Get HTML Page Source

Core

Retrieves the raw, serialized HTML source code of the active web document.

String pageSource = driver.getPageSource();
ID: #11
Browser Control

Maximize Browser Window

Core

Maximizes the browser window to fill the display boundaries of the current screen.

driver.manage().window().maximize();
πŸ’‘

Pro-Tip: Execute this command immediately after instantiating the driver to ensure responsive layouts render consistently.

ID: #12
Browser Control

Minimize Browser Window

Core

Minimizes the browser window to the operating system taskbar.

driver.manage().window().minimize();
ID: #13
Browser Control

Fullscreen Browser Window

Core

Puts the browser window into standard OS-level borderless presentation fullscreen mode.

driver.manage().window().fullscreen();
ID: #14
Browser Control

Get Window Dimension

Core

Retrieves the width and height resolution coordinates of the active window in pixels.

Dimension size = driver.manage().window().getSize();
ID: #15
Browser Control

Close Active Window (Tab)

Core

Closes the currently active browser window or tab. If it is the last open window, the entire driver session is terminated.

driver.close();
πŸ’‘

Pro-Tip: Ideal for cleaning up multiple spawned popups or child windows without killing the entire session.

ID: #16
Browser Control

Quit WebDriver Session

Core

Closes all open windows and tabs, terminates the underlying driver service process, and releases system resources safely.

driver.quit();
πŸ’‘

Pro-Tip: Always run this in the tearDown or @AfterMethod hook to prevent orphan processes from consuming server RAM.

ID: #17
Browser Control

Set Page Load Strategy

Advanced

Configures the browser startup options to use the EAGER page load strategy, which instructs the driver to wait only until the initial HTML document is parsed (DOMContentLoaded) rather than waiting for all stylesheets, subframes, and images to load.

ChromeOptions options = new ChromeOptions();
options.setPageLoadStrategy(PageLoadStrategy.EAGER);
ID: #18
Locators

Find Element by ID

Core

Locates a single element matching the unique 'id' attribute in the DOM tree.

WebElement el = driver.findElement(By.id("submit-btn"));
ID: #19
Locators

Find Element by Name

Core

Locates an element matching the 'name' input attribute.

WebElement input = driver.findElement(By.name("username"));
ID: #20
Locators

Find Element by XPath

Core

Locates an element utilizing standard XML Path Language selectors. Supports highly customizable hierarchy navigations.

WebElement el = driver.findElement(By.xpath("//button[@type='submit']"));
ID: #21
Locators

Find Element by CSS Selector

Core

Locates an element using native browser stylesheet queries. Faster and highly recommended over XPath.

WebElement el = driver.findElement(By.cssSelector("div.container > button#save"));
πŸ’‘

Pro-Tip: Use CSS Selectors for styling sheets and XPath only when traversing upwards in the DOM tree.

ID: #22
Locators

Find Element by Class Name

Core

Locates an element matching a specific CSS class attribute.

WebElement el = driver.findElement(By.className("btn-primary"));
ID: #23
Locators

Find Element by Tag Name

Core

Locates an element matching the specified HTML tag name.

WebElement heading = driver.findElement(By.tagName("h1"));
ID: #24
Locators

Find Element by Link Text

Core

Locates an anchor <a> element matching the exact visible inner text string.

WebElement link = driver.findElement(By.linkText("Forgot Password?"));
ID: #25
Locators

Find Element by Partial Link Text

Core

Locates an anchor <a> element containing the specified substring in its visible inner text.

WebElement link = driver.findElement(By.partialLinkText("Forgot"));
ID: #26
Locators

Find Multiple Elements

Core

Locates all elements matching the locator. Returns an empty list instead of throwing an exception if nothing is found.

List<WebElement> rows = driver.findElements(By.tagName("tr"));
πŸ’‘

Pro-Tip: Always use findElements() to safely check for the presence or absence of dynamic elements without triggering NoSuchElementException.

ID: #27
Locators

Relative Locator (Above)

Advanced

Locates an element positioned physically above another known reference element in the viewport layout.

WebElement input = driver.findElement(RelativeLocator.with(By.tagName("input")).above(referenceElement));
πŸ’‘

Pro-Tip: Import static org.openqa.selenium.support.locators.RelativeLocator.*; for cleaner code syntax.

ID: #28
Locators

Relative Locator (Below)

Advanced

Locates an element positioned physically below another known reference element.

WebElement label = driver.findElement(RelativeLocator.with(By.tagName("label")).below(referenceElement));
ID: #29
Locators

Relative Locator (Near)

Advanced

Locates an element located within a specific pixel distance (e.g. 50px) of a reference element.

WebElement button = driver.findElement(RelativeLocator.with(By.tagName("button")).near(referenceElement, 50));
ID: #30
Locators

Advanced XPath Axis Traversal

Advanced

Navigates forward through sibling elements under the same parent node in the DOM structure.

WebElement el = driver.findElement(By.xpath("//input[@id='username']/following-sibling::span"));
ID: #31
Locators

Locate Multiple Sibling Elements

Advanced

Finds all sibling elements located before the specified reference node in the tree.

List<WebElement> elements = driver.findElements(By.xpath("//li[@class='active']/preceding-sibling::li"));
ID: #32
Element Interactions

Click Element

Core

Clicks the target element. Will scroll the element into view first if needed.

element.click();
ID: #33
Element Interactions

Type Text (Send Keys)

Core

Types the specified text string into a text input or textarea element.

element.sendKeys("AdminPass123");
ID: #34
Element Interactions

Clear Input Text

Core

Clears any pre-existing text content in an input or textarea element.

element.clear();
ID: #35
Element Interactions

Submit HTML Form

Core

Submits the parent HTML <form> containing the target element. Convenient shortcut for submitting forms.

element.submit();
ID: #36
Element Interactions

Get Visible Text

Core

Retrieves the visible inner text of the element, including sub-elements, excluding hidden CSS spaces.

String text = element.getText();
ID: #37
Element Interactions

Get Element Attribute

Core

Retrieves the value of a specific HTML attribute (e.g., placeholder, value, class) on the element.

String val = element.getAttribute("placeholder");
ID: #38
Element Interactions

Is Element Displayed

Core

Returns true if the element is currently visible to the end user in the browser viewport.

boolean isVisible = element.isDisplayed();
ID: #39
Element Interactions

Is Element Enabled

Core

Returns true if the input element is enabled (does not contain the disabled attribute).

boolean isEnabled = element.isEnabled();
ID: #40
Element Interactions

Is Checkbox Selected

Core

Checks if a checkbox, radio button, or option element is currently selected.

boolean isSelected = element.isSelected();
ID: #41
Element Interactions

Get Element Size

Core

Returns the width and height dimensions of the rendered WebElement bounds.

Dimension dim = element.getSize();
ID: #42
Element Interactions

Get Element Location

Core

Returns the top-left x and y coordinates of the element relative to the document page.

Point location = element.getLocation();
ID: #43
Element Interactions

Get Element Rect

Core

Retrieves both size and location parameters simultaneously in a single, high-performance API query.

Rectangle rect = element.getRect();
ID: #44
Element Interactions

Get Computed CSS Value

Core

Retrieves the resolved value of a CSS property (like color, font-size) currently applied to the element.

String color = element.getCssValue("background-color");
ID: #45
Element Interactions

Find Sub-Element (Scoped search)

Core

Restricts the search query strictly within the boundaries of the parent element's inner DOM tree.

WebElement subEl = parentElement.findElement(By.className("child"));
πŸ’‘

Pro-Tip: Greatly limits matching scope and makes your scripts more robust in large lists or tables.

ID: #46
Element Interactions

Get Element Tag Name

Core

Fetches the node's standard tag name string (e.g. div, input, select).

String tag = element.getTagName();
ID: #47
Element Interactions

Check Element Focus

Advanced

Verifies if the target element holds active document-level focus inside the browser session.

boolean isFocused = element.equals(driver.switchTo().activeElement());
ID: #48
Waits & Synchronization

Implicit Timeout Wait

Core

Specifies the amount of time the driver should wait when searching for an element before throwing NoSuchElementException.

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
πŸ’‘

Pro-Tip: Avoid mixing this with Explicit Waits as it leads to unpredictable wait timeouts!

ID: #49
Waits & Synchronization

Explicit Wait Initiation

Core

Instantiates a new WebDriverWait instance utilizing Selenium 4 Duration-based intervals.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
ID: #50
Waits & Synchronization

Wait until Element is Visible

Core

Suspends execution until the located element is rendered visible on the screen.

WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("metrics")));
ID: #51
Waits & Synchronization

Wait until Element is Clickable

Core

Waits until an element is present, visible, and enabled in the browser viewport so it can receive clicks.

WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
ID: #52
Waits & Synchronization

Wait until Text is Present

Core

Waits until the text inside the located element matches the expected string.

boolean isPresent = wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("status"), "Completed"));
ID: #53
Waits & Synchronization

Wait for Element Invisibility

Core

Synchronizes the flow by waiting until a temporary overlay (like a loading spinner) disappears from the screen.

boolean isInvisible = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("spinner")));
ID: #54
Waits & Synchronization

Fluent Wait Setup

Advanced

Defines a dynamic wait checking the DOM at fixed intervals and ignoring specific exceptions during polling.

Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(15))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);
ID: #55
Waits & Synchronization

ExpectedConditions Refreshed

Advanced

Wraps another expected condition to auto-locate elements when StaleElementReferenceException is hit.

wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(By.id("save"))));
ID: #56
Waits & Synchronization

Hardcoded Static Sleep

Core

Blocks the Java execution thread for a fixed duration. Strong anti-pattern in clean production framework builds.

Thread.sleep(2000);
πŸ’‘

Pro-Tip: ❌ Never commit Thread.sleep() to production code! Use WebDriverWait dynamic conditions instead.

ID: #57
Waits & Synchronization

Wait for Page Load Completion

Advanced

Evaluates the document readyState using JavaScript Executor to verify page assets are fully parsed.

wait.until(d -> ((JavascriptExecutor) d).executeScript("return document.readyState").equals("complete"));
ID: #58
Waits & Synchronization

Set Page Load Timeout Limits

Advanced

Configures a timeout limit for loading pages. Raises a TimeoutException if the page takes longer than the duration specified.

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
ID: #59
Waits & Synchronization

Set Async Script Execution Timeout

Advanced

Limits the execution duration allocated for asynchronous Javascript code to complete execution.

driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(15));
ID: #60
Waits & Synchronization

Wait until Element Stops Moving

Advanced

Compares coordinates over a short interval to ensure an animated element is physically stable before interaction.

wait.until(d -> {
    Point p1 = element.getLocation();
    try { Thread.sleep(100); } catch (Exception e) {}
    Point p2 = element.getLocation();
    return p1.equals(p2);
});
ID: #61
Waits & Synchronization

Wait until Custom Javascript Condition returns True

Advanced

Suspends the execution flow until a custom javascript statement evaluates to true (e.g. pending JQuery requests complete).

wait.until(d -> (Boolean) ((JavascriptExecutor) d).executeScript("return window.jQuery.active == 0;"));
ID: #62
Alerts & Popups

Switch to Alert Box

Core

Switches context focus to the active browser dialog alert modal popup.

Alert alert = driver.switchTo().alert();
ID: #63
Alerts & Popups

Accept Browser Alert

Core

Simulates clicking 'OK' or 'Accept' on a JavaScript confirm, alert, or prompt box.

driver.switchTo().alert().accept();
ID: #64
Alerts & Popups

Dismiss Browser Alert

Core

Simulates clicking 'Cancel' or 'Dismiss' on a JavaScript dialog box.

driver.switchTo().alert().dismiss();
ID: #65
Alerts & Popups

Get Text from Alert

Core

Retrieves the inner text string inside the active browser prompt or confirm box.

String alertText = driver.switchTo().alert().getText();
ID: #66
Alerts & Popups

Type inside Prompt Alert

Core

Types a string input value into the text area prompt of a JavaScript prompt modal.

driver.switchTo().alert().sendKeys("Confirmed");
ID: #67
Alerts & Popups

Switch to Frame by Name/ID

Core

Switches context target focus into an iframe element using its Name or ID attribute.

driver.switchTo().frame("iframe-host");
ID: #68
Alerts & Popups

Switch to Frame by Index

Core

Switches context to the first (index 0) iframe container on the webpage.

driver.switchTo().frame(0);
ID: #69
Alerts & Popups

Switch to Frame by WebElement

Core

Switches context to an iframe after locating it as a standard WebElement.

WebElement frameEl = driver.findElement(By.cssSelector("iframe.payment"));
driver.switchTo().frame(frameEl);
ID: #70
Alerts & Popups

Switch back to Default Content

Core

Exits all iframe levels, returning focus back to the top-level main page document.

driver.switchTo().defaultContent();
ID: #71
Alerts & Popups

Get Active Window Handle ID

Core

Returns a unique tab or window identifier string associated with the currently focused viewport.

String handle = driver.getWindowHandle();
ID: #72
Alerts & Popups

Get All Window Handle IDs

Core

Returns a set of unique window identifier handles for all open tabs or browser windows.

Set<String> handles = driver.getWindowHandles();
ID: #73
Alerts & Popups

Switch Window Context

Core

Switches context focus to a specific tab or window matching the target handle ID.

driver.switchTo().window(windowId);
ID: #74
Alerts & Popups

Switch to New Tab Context

Advanced

Selenium 4 native API to create and switch context directly into a brand new browser tab.

driver.switchTo().newWindow(WindowType.TAB);
ID: #75
Dropdown Controls

Select Option by Text

Core

Selects an option inside an HTML <select> tag matching the exact visible label text.

new Select(dropdownElement).selectByVisibleText("India");
ID: #76
Dropdown Controls

Select Option by Value

Core

Selects an option inside a <select> tag matching the 'value' HTML attribute.

new Select(dropdownElement).selectByValue("IN");
ID: #77
Dropdown Controls

Select Option by Index

Core

Selects an option inside a <select> tag based on its zero-indexed list order (e.g. index 1 selects 2nd option).

new Select(dropdownElement).selectByIndex(1);
ID: #78
Dropdown Controls

Deselect All Options

Core

Clears all selected option choices. Note: Only works inside multi-select dropdown controls.

new Select(dropdownElement).deselectAll();
ID: #79
Dropdown Controls

Get All Selected Options

Core

Returns a list of all currently highlighted choice elements in a multi-select dropdown.

List<WebElement> options = new Select(dropdownElement).getAllSelectedOptions();
ID: #80
Dropdown Controls

Check Multi-Select Dropdown

Core

Verifies if the target dropdown allows selecting multiple values simultaneously.

boolean isMulti = new Select(dropdownElement).isMultiple();
ID: #81
Dropdown Controls

Deselect Option by Visible Text

Core

Deselects a previously chosen dropdown option using its visible textual label.

new Select(dropdownElement).deselectByVisibleText("India");
ID: #82
Actions API

Mouse Hover (Move to Element)

Core

Simulates moving the mouse cursor to the center coordinates of the target element.

new Actions(driver).moveToElement(el).perform();
πŸ’‘

Pro-Tip: Always append .perform() at the end of Actions chains to dispatch the command to the browser!

ID: #83
Actions API

Double Click

Core

Performs a fast simulated double-click click sequence on the target element.

new Actions(driver).doubleClick(el).perform();
ID: #84
Actions API

Context Click (Right-Click)

Core

Performs a right-click click action to open element-specific browser contextual menus.

new Actions(driver).contextClick(el).perform();
ID: #85
Actions API

Drag and Drop

Core

Drags the source element and releases it over the target element location.

new Actions(driver).dragAndDrop(sourceEl, targetEl).perform();
ID: #86
Actions API

Click and Hold

Core

Performs a mouse click down event on the element without releasing it.

new Actions(driver).clickAndHold(el).perform();
ID: #87
Actions API

Release Mouse Hold

Core

Releases any active click-hold action at the current mouse pointer coordinate.

new Actions(driver).release().perform();
ID: #88
Actions API

Keyboard Key Press

Core

Sends a keyboard key stroke to the element currently holding focus.

new Actions(driver).sendKeys(Keys.ENTER).perform();
ID: #89
Actions API

Keyboard Key Down

Core

Simulates holding down a keyboard key (like SHIFT, CTRL) without releasing it.

new Actions(driver).keyDown(Keys.SHIFT).perform();
ID: #90
Actions API

Keyboard Key Up

Core

Releases a held keyboard key (like SHIFT, CTRL).

new Actions(driver).keyUp(Keys.SHIFT).perform();
ID: #91
Actions API

Key Combo (Copy Shortcut)

Advanced

Chains actions together to dispatch keyboard combinations (e.g., Ctrl+C).

new Actions(driver).keyDown(Keys.CONTROL).sendKeys("c").keyUp(Keys.CONTROL).perform();
ID: #92
Actions API

Scroll to Element (Actions)

Core

Selenium 4 Actions shortcut that scrolls the viewport until the target element is visible.

new Actions(driver).scrollToElement(el).perform();
ID: #93
Actions API

Drag & Drop by Offset

Core

Drags an element and moves it to horizontal/vertical coordinate pixel offsets.

new Actions(driver).dragAndDropBy(sourceEl, 100, 0).perform();
ID: #94
Actions API

Move Mouse to Specific Coordinates

Advanced

Moves the mouse pointer relative to its current screen coordinates and dispatches a click event.

new Actions(driver).moveByOffset(150, 200).click().perform();
ID: #95
JavaScript Executor

JavaScript Scroll by Pixels

Advanced

Scrolls the page layout down by 500 vertical pixels using dynamic Javascript engine commands.

((JavascriptExecutor) driver).executeScript("window.scrollBy(0, 500);");
ID: #96
JavaScript Executor

JavaScript Scroll into View

Advanced

Scrolls the page until the target element aligns at the center of the active browser viewport.

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block: 'center'});", el);
ID: #97
JavaScript Executor

JavaScript Force Click

Advanced

Clicks the element directly through browser dispatch. Bypasses viewport overlaps and display checks.

((JavascriptExecutor) driver).executeScript("arguments[0].click();", el);
πŸ’‘

Pro-Tip: Use strictly as a fallback! JS clicks bypass browser interactive validations (like overlays or disabled states).

ID: #98
JavaScript Executor

Highlight Element in UI

Advanced

Injects styling rules to apply a colorful solid border around the element, extremely useful for visual debugging.

((JavascriptExecutor) driver).executeScript("arguments[0].style.border='3px solid orange';", el);
ID: #99
JavaScript Executor

Retrieve Hidden Input Value

Advanced

Fetches hidden attribute values directly from input elements where element.getText() returns empty strings.

String val = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].value;", el);
ID: #100
JavaScript Executor

Scroll to Bottom of Page

Advanced

Scrolls down to the very bottom boundary of the page height.

((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
ID: #101
JavaScript Executor

Get Window Inner Height

Advanced

Retrieves the actual responsive height pixel dimension of the browser layout.

long viewportHeight = (Long) ((JavascriptExecutor) driver).executeScript("return window.innerHeight;");
ID: #102
JavaScript Executor

Bypass Hidden Element Display

Advanced

Dynamically edits the DOM styling to display hidden background inputs.

((JavascriptExecutor) driver).executeScript("arguments[0].style.display='block';", el);
ID: #103
JavaScript Executor

Set Input Value via JS

Advanced

Bypasses standard user input events to assign value properties directly to form inputs using JS.

((JavascriptExecutor) driver).executeScript("arguments[0].value='custom_val';", el);
ID: #104
JavaScript Executor

Inject Dynamic CSS Style Block

Advanced

Injects stylesheet declarations directly into the HTML head container, extremely useful for disabling transitions during automation execution.

((JavascriptExecutor) driver).executeScript("var s=document.createElement('style');s.innerHTML='* { transition: none !important; }';document.head.appendChild(s);");
ID: #105
Cookies & Storage

Add Session Cookie

Advanced

Injects a custom authentication cookie into the active browser profile context.

driver.manage().addCookie(new Cookie("auth-token", "qa-session-token"));
πŸ’‘

Pro-Tip: Ensure the active tab matches the target cookie domain before calling this command!

ID: #106
Cookies & Storage

Delete Cookie by Name

Advanced

Deletes a specific cookie identifier from the active session.

driver.manage().deleteCookieNamed("session-id");
ID: #107
Cookies & Storage

Delete All Browser Cookies

Core

Deletes every single session cookie, useful in clean teardowns to force logouts.

driver.manage().deleteAllCookies();
ID: #108
Cookies & Storage

Retrieve Active Cookie

Advanced

Fetches a specific cookie object containing domain, value, path, and expiry metadata.

Cookie cookie = driver.manage().getCookieNamed("auth-token");
ID: #109
Cookies & Storage

Clear Browser LocalStorage

Advanced

Wipes local web storage variables via JavaScript executor, commonly required for session cleanup.

((JavascriptExecutor) driver).executeScript("window.localStorage.clear();");
ID: #110
Cookies & Storage

Clear SessionStorage

Advanced

Wipes volatile session storage variables to clear temporary client session states.

((JavascriptExecutor) driver).executeScript("window.sessionStorage.clear();");
ID: #111
Diagnostics

Capture Full-Page Screenshot

Core

Captures a full visual image capture of the current active browser layout frame.

File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
ID: #112
Diagnostics

Capture Element Screenshot

Core

Selenium 4 native screenshot feature that captures only the specific bounding box of a target WebElement.

File srcFile = element.getScreenshotAs(OutputType.FILE);
πŸ’‘

Pro-Tip: Extremely helpful for auditing charts, barcodes, or custom widgets!

ID: #113
Diagnostics

Switch to Active Element

Advanced

Fetches the node holding document-focus, commonly used for tab navigation testing.

WebElement activeEl = driver.switchTo().activeElement();
ID: #114
Diagnostics

Retrieve Element Location in Viewport

Core

Fetches screen coordinate offsets relative to the viewport layout.

Point point = element.getLocation();
ID: #115
Diagnostics

Wait for Alert Box presence

Core

Explicit wait that pauses execution until a native browser alert is active and visible.

Alert alert = wait.until(ExpectedConditions.alertIsPresent());
ID: #116
Diagnostics

Emulate Geolocation via CDP DevTools

Advanced

Intercepts browser device location calls utilizing the Chromium DevTools Protocol (CDP) to test location-dependent dynamic content.

DevTools devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();
devTools.send(Emulation.setGeolocationOverride(
    Optional.of(40.7128), Optional.of(-74.0060), Optional.of(1)));
ID: #117
Diagnostics

Throttle Network Speed via CDP DevTools

Advanced

Throttles browser connection throughput and latency parameters to emulate slow 3G or custom network connections.

DevTools devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();
devTools.send(Network.emulateNetworkConditions(
    false, 100, 250000, 500000, Optional.of(ConnectionType.WIFI)));
ID: #118
Test Frameworks

TestNG Before Method Hook

Framework

TestNG runner hook that executes before every individual test method. Perfect for driver setup.

@BeforeMethod
public void setUp() {
    driver = new ChromeDriver();
}
ID: #119
Test Frameworks

TestNG After Method Hook

Framework

TestNG runner hook that executes immediately after each test completes. Closes active windows.

@AfterMethod
public void tearDown() {
    if (driver != null) driver.quit();
}
ID: #120
Test Frameworks

TestNG Test Method Definition

Framework

Marks a method as an executable test case. Allows defining execution order and custom retries.

@Test(priority = 1, retryAnalyzer = Retry.class)
public void verifyLoginFlow() {
    // test script
}
ID: #121
Test Frameworks

TestNG Parameter Injection

Framework

Injects environment and parameter inputs from testng.xml configurations.

@Parameters({"browser", "env"})
@BeforeClass
public void initConfig(String browser, String env) {
    // cross-browser config
}
ID: #122
Test Frameworks

TestNG DataProvider Injection

Framework

Declares a data provider method returning object arrays to drive parameterized data-driven executions.

@DataProvider(name = "loginData")
public Object[][] getData() {
    return new Object[][] {
        { "user1", "pass1" },
        { "user2", "pass2" }
    };
}
ID: #123
Test Frameworks

Assertion - Check Equality

Framework

Hard assertion that compares strings, arrays, or objects and fails the test instantly on a mismatch.

Assert.assertEquals(actualText, expectedText, "Text verification failed!");
ID: #124
Test Frameworks

Assertion - Check Condition

Framework

Hard assertion validating that a conditional expression evaluates to true.

Assert.assertTrue(element.isDisplayed(), "Element is not visible!");
ID: #125
Test Frameworks

JUnit 5 Test Annotation

Framework

JUnit 5 standard runner annotation to execute test functions.

@Test
@DisplayName("Validate Checkout")
public void testCheckout() {
    // junit 5 syntax
}
ID: #126
Test Frameworks

Soft Assertion Initiation

Framework

Soft assertion that continues running subsequent assertions on failure and reports compile failures at assertAll().

SoftAssert softAssert = new SoftAssert();
softAssert.assertTrue(isHeadingVisible);
softAssert.assertAll();
πŸ’‘

Pro-Tip: Always invoke softAssert.assertAll() at the very end of your test case to compile the final failures!

ID: #127
Test Frameworks

Verify Element Not Present

Framework

Locates elements safely via dynamic findElements check, asserting that the target node is not present in DOM.

boolean isPresent = !driver.findElements(By.id("error-msg")).isEmpty();
Assert.assertFalse(isPresent, "Error was unexpected!");
ID: #128
Framework Architecture

PageFactory Model Initialization

Framework

Initializes Page Factory elements declared under @FindBy annotations in Page Objects.

PageFactory.initElements(driver, this);
ID: #129
Framework Architecture

FindBy Selector Annotation

Framework

Declares element matching selectors inside Page Objects. Elements are lazily located on usage.

@FindBy(css = "input[data-testid='user-input']")
private WebElement usernameInput;
ID: #130
Framework Architecture

Logger Output Info Message

Framework

Logs framework action details utilizing standard robust SLF4J/Log4j libraries.

private static final Logger log = LoggerFactory.getLogger(LoginPage.class);
log.info("Submitting credentials for user");
ID: #131
Framework Architecture

Logger Output Error Message

Framework

Logs debug trace error points to files and reports when assertions or exceptions are thrown.

log.error("Exception occurred while completing flow: {}", e.getMessage());
ID: #132
Framework Architecture

Read Framework Property Configurations

Framework

Loads external config property files to centralize urls, logins, and env parameters.

Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
String val = prop.getProperty("base.url");
ID: #133
Framework Architecture

Write File Logger Output

Framework

Writes data lines or debug audit logs directly to standard text files in the project workspace.

FileWriter fw = new FileWriter("results.txt", true);
fw.write("Test Case Passed\n");
fw.close();
ID: #134
Framework Architecture

Handle File Upload (SendKeys bypass)

Core

Safely uploads files by typing the absolute file path directly into the hidden file input element tag.

WebElement uploadInput = driver.findElement(By.cssSelector("input[type='file']"));
uploadInput.sendKeys("C:\\qa-assets\\invoice.pdf");
πŸ’‘

Pro-Tip: Bypasses standard file-dialog windows entirely. This is highly compatible with headless execution grids!

ID: #135
Framework Architecture

Verify Completed File Download

Framework

Verifies the presence of a downloaded file inside target project local directory folders.

File file = new File("C:\\Downloads\\statement.pdf");
boolean isDownloaded = file.exists();
ID: #136
Framework Architecture

Shadow DOM SearchContext traversal

Advanced

Selenium 4 modern API to query encapsulated shadow DOM elements using native context boundaries.

SearchContext shadow = driver.findElement(By.id("shadow-host")).getShadowRoot();
WebElement target = shadow.findElement(By.cssSelector("input#nested"));
ID: #137
Framework Architecture

Headless Browser Configuration

Framework

Configures Chrome to run in modern background headless mode, vital for Docker and Jenkins CI execution pipelines.

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
options.addArguments("--window-size=1920,1080");
ID: #138
Framework Architecture

Configure Incognito Mode

Core

Configures browser context execution to run in isolated Incognito / Private layout settings.

ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
ID: #139
Framework Architecture

Selenium Grid RemoteWebDriver Setup

Framework

Directs automation script actions to a remote Selenium Grid Hub router instead of launching local browsers.

WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444"), options);
ID: #140

Want to practice in real life?

Open our custom built **QA Playground** to test these commands against active dynamic lists, AJAX forms, calendar pickers, loading spinners, and multi-iframe boxes.