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.
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!
Launch Chrome Browser
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.
Launch Firefox Browser
Instantiates a new FirefoxDriver instance using the native Geckodriver protocol to launch a Mozilla Firefox browser session.
WebDriver driver = new FirefoxDriver();Launch Edge Browser
Instantiates a new EdgeDriver instance to control a Chromium-based Microsoft Edge browser session.
WebDriver driver = new EdgeDriver();Open Web Page (Get)
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.
Navigate to URL
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");Navigate Backwards
Simulates clicking the browser's native 'Back' button in history.
driver.navigate().back();Navigate Forwards
Simulates clicking the browser's native 'Forward' button in history.
driver.navigate().forward();Refresh Page
Reloads the current active document in the browser window.
driver.navigate().refresh();Get Page Title
Retrieves the document title of the active webpage.
String title = driver.getTitle();Get Current URL
Retrieves the complete, absolute URL string of the webpage currently active in the viewport.
String currentUrl = driver.getCurrentUrl();Get HTML Page Source
Retrieves the raw, serialized HTML source code of the active web document.
String pageSource = driver.getPageSource();Maximize Browser Window
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.
Minimize Browser Window
Minimizes the browser window to the operating system taskbar.
driver.manage().window().minimize();Fullscreen Browser Window
Puts the browser window into standard OS-level borderless presentation fullscreen mode.
driver.manage().window().fullscreen();Get Window Dimension
Retrieves the width and height resolution coordinates of the active window in pixels.
Dimension size = driver.manage().window().getSize();Close Active Window (Tab)
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.
Quit WebDriver Session
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.
Set Page Load Strategy
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);Find Element by ID
Locates a single element matching the unique 'id' attribute in the DOM tree.
WebElement el = driver.findElement(By.id("submit-btn"));Find Element by Name
Locates an element matching the 'name' input attribute.
WebElement input = driver.findElement(By.name("username"));Find Element by XPath
Locates an element utilizing standard XML Path Language selectors. Supports highly customizable hierarchy navigations.
WebElement el = driver.findElement(By.xpath("//button[@type='submit']"));Find Element by CSS Selector
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.
Find Element by Class Name
Locates an element matching a specific CSS class attribute.
WebElement el = driver.findElement(By.className("btn-primary"));Find Element by Tag Name
Locates an element matching the specified HTML tag name.
WebElement heading = driver.findElement(By.tagName("h1"));Find Element by Link Text
Locates an anchor <a> element matching the exact visible inner text string.
WebElement link = driver.findElement(By.linkText("Forgot Password?"));Find Element by Partial Link Text
Locates an anchor <a> element containing the specified substring in its visible inner text.
WebElement link = driver.findElement(By.partialLinkText("Forgot"));Find Multiple Elements
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.
Relative Locator (Above)
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.
Relative Locator (Below)
Locates an element positioned physically below another known reference element.
WebElement label = driver.findElement(RelativeLocator.with(By.tagName("label")).below(referenceElement));Relative Locator (Near)
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));Advanced XPath Axis Traversal
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"));Locate Multiple Sibling Elements
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"));Click Element
Clicks the target element. Will scroll the element into view first if needed.
element.click();Type Text (Send Keys)
Types the specified text string into a text input or textarea element.
element.sendKeys("AdminPass123");Clear Input Text
Clears any pre-existing text content in an input or textarea element.
element.clear();Submit HTML Form
Submits the parent HTML <form> containing the target element. Convenient shortcut for submitting forms.
element.submit();Get Visible Text
Retrieves the visible inner text of the element, including sub-elements, excluding hidden CSS spaces.
String text = element.getText();Get Element Attribute
Retrieves the value of a specific HTML attribute (e.g., placeholder, value, class) on the element.
String val = element.getAttribute("placeholder");Is Element Displayed
Returns true if the element is currently visible to the end user in the browser viewport.
boolean isVisible = element.isDisplayed();Is Element Enabled
Returns true if the input element is enabled (does not contain the disabled attribute).
boolean isEnabled = element.isEnabled();Is Checkbox Selected
Checks if a checkbox, radio button, or option element is currently selected.
boolean isSelected = element.isSelected();Get Element Size
Returns the width and height dimensions of the rendered WebElement bounds.
Dimension dim = element.getSize();Get Element Location
Returns the top-left x and y coordinates of the element relative to the document page.
Point location = element.getLocation();Get Element Rect
Retrieves both size and location parameters simultaneously in a single, high-performance API query.
Rectangle rect = element.getRect();Get Computed CSS Value
Retrieves the resolved value of a CSS property (like color, font-size) currently applied to the element.
String color = element.getCssValue("background-color");Find Sub-Element (Scoped search)
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.
Get Element Tag Name
Fetches the node's standard tag name string (e.g. div, input, select).
String tag = element.getTagName();Check Element Focus
Verifies if the target element holds active document-level focus inside the browser session.
boolean isFocused = element.equals(driver.switchTo().activeElement());Implicit Timeout Wait
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!
Explicit Wait Initiation
Instantiates a new WebDriverWait instance utilizing Selenium 4 Duration-based intervals.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));Wait until Element is Visible
Suspends execution until the located element is rendered visible on the screen.
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("metrics")));Wait until Element is Clickable
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")));Wait until Text is Present
Waits until the text inside the located element matches the expected string.
boolean isPresent = wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("status"), "Completed"));Wait for Element Invisibility
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")));Fluent Wait Setup
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);ExpectedConditions Refreshed
Wraps another expected condition to auto-locate elements when StaleElementReferenceException is hit.
wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(By.id("save"))));Hardcoded Static Sleep
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.
Wait for Page Load Completion
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"));Set Page Load Timeout Limits
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));Set Async Script Execution Timeout
Limits the execution duration allocated for asynchronous Javascript code to complete execution.
driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(15));Wait until Element Stops Moving
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);
});Wait until Custom Javascript Condition returns True
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;"));Switch to Alert Box
Switches context focus to the active browser dialog alert modal popup.
Alert alert = driver.switchTo().alert();Accept Browser Alert
Simulates clicking 'OK' or 'Accept' on a JavaScript confirm, alert, or prompt box.
driver.switchTo().alert().accept();Dismiss Browser Alert
Simulates clicking 'Cancel' or 'Dismiss' on a JavaScript dialog box.
driver.switchTo().alert().dismiss();Get Text from Alert
Retrieves the inner text string inside the active browser prompt or confirm box.
String alertText = driver.switchTo().alert().getText();Type inside Prompt Alert
Types a string input value into the text area prompt of a JavaScript prompt modal.
driver.switchTo().alert().sendKeys("Confirmed");Switch to Frame by Name/ID
Switches context target focus into an iframe element using its Name or ID attribute.
driver.switchTo().frame("iframe-host");Switch to Frame by Index
Switches context to the first (index 0) iframe container on the webpage.
driver.switchTo().frame(0);Switch to Frame by WebElement
Switches context to an iframe after locating it as a standard WebElement.
WebElement frameEl = driver.findElement(By.cssSelector("iframe.payment"));
driver.switchTo().frame(frameEl);Switch back to Default Content
Exits all iframe levels, returning focus back to the top-level main page document.
driver.switchTo().defaultContent();Get Active Window Handle ID
Returns a unique tab or window identifier string associated with the currently focused viewport.
String handle = driver.getWindowHandle();Get All Window Handle IDs
Returns a set of unique window identifier handles for all open tabs or browser windows.
Set<String> handles = driver.getWindowHandles();Switch Window Context
Switches context focus to a specific tab or window matching the target handle ID.
driver.switchTo().window(windowId);Switch to New Tab Context
Selenium 4 native API to create and switch context directly into a brand new browser tab.
driver.switchTo().newWindow(WindowType.TAB);Select Option by Text
Selects an option inside an HTML <select> tag matching the exact visible label text.
new Select(dropdownElement).selectByVisibleText("India");Select Option by Value
Selects an option inside a <select> tag matching the 'value' HTML attribute.
new Select(dropdownElement).selectByValue("IN");Select Option by Index
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);Deselect All Options
Clears all selected option choices. Note: Only works inside multi-select dropdown controls.
new Select(dropdownElement).deselectAll();Get All Selected Options
Returns a list of all currently highlighted choice elements in a multi-select dropdown.
List<WebElement> options = new Select(dropdownElement).getAllSelectedOptions();Check Multi-Select Dropdown
Verifies if the target dropdown allows selecting multiple values simultaneously.
boolean isMulti = new Select(dropdownElement).isMultiple();Deselect Option by Visible Text
Deselects a previously chosen dropdown option using its visible textual label.
new Select(dropdownElement).deselectByVisibleText("India");Mouse Hover (Move to Element)
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!
Double Click
Performs a fast simulated double-click click sequence on the target element.
new Actions(driver).doubleClick(el).perform();Context Click (Right-Click)
Performs a right-click click action to open element-specific browser contextual menus.
new Actions(driver).contextClick(el).perform();Drag and Drop
Drags the source element and releases it over the target element location.
new Actions(driver).dragAndDrop(sourceEl, targetEl).perform();Click and Hold
Performs a mouse click down event on the element without releasing it.
new Actions(driver).clickAndHold(el).perform();Release Mouse Hold
Releases any active click-hold action at the current mouse pointer coordinate.
new Actions(driver).release().perform();Keyboard Key Press
Sends a keyboard key stroke to the element currently holding focus.
new Actions(driver).sendKeys(Keys.ENTER).perform();Keyboard Key Down
Simulates holding down a keyboard key (like SHIFT, CTRL) without releasing it.
new Actions(driver).keyDown(Keys.SHIFT).perform();Keyboard Key Up
Releases a held keyboard key (like SHIFT, CTRL).
new Actions(driver).keyUp(Keys.SHIFT).perform();Key Combo (Copy Shortcut)
Chains actions together to dispatch keyboard combinations (e.g., Ctrl+C).
new Actions(driver).keyDown(Keys.CONTROL).sendKeys("c").keyUp(Keys.CONTROL).perform();Scroll to Element (Actions)
Selenium 4 Actions shortcut that scrolls the viewport until the target element is visible.
new Actions(driver).scrollToElement(el).perform();Drag & Drop by Offset
Drags an element and moves it to horizontal/vertical coordinate pixel offsets.
new Actions(driver).dragAndDropBy(sourceEl, 100, 0).perform();Move Mouse to Specific Coordinates
Moves the mouse pointer relative to its current screen coordinates and dispatches a click event.
new Actions(driver).moveByOffset(150, 200).click().perform();JavaScript Scroll by Pixels
Scrolls the page layout down by 500 vertical pixels using dynamic Javascript engine commands.
((JavascriptExecutor) driver).executeScript("window.scrollBy(0, 500);");JavaScript Scroll into View
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);JavaScript Force Click
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).
Highlight Element in UI
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);Retrieve Hidden Input Value
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);Scroll to Bottom of Page
Scrolls down to the very bottom boundary of the page height.
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");Get Window Inner Height
Retrieves the actual responsive height pixel dimension of the browser layout.
long viewportHeight = (Long) ((JavascriptExecutor) driver).executeScript("return window.innerHeight;");Bypass Hidden Element Display
Dynamically edits the DOM styling to display hidden background inputs.
((JavascriptExecutor) driver).executeScript("arguments[0].style.display='block';", el);Set Input Value via JS
Bypasses standard user input events to assign value properties directly to form inputs using JS.
((JavascriptExecutor) driver).executeScript("arguments[0].value='custom_val';", el);Inject Dynamic CSS Style Block
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);");Add Session Cookie
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!
Delete Cookie by Name
Deletes a specific cookie identifier from the active session.
driver.manage().deleteCookieNamed("session-id");Delete All Browser Cookies
Deletes every single session cookie, useful in clean teardowns to force logouts.
driver.manage().deleteAllCookies();Retrieve Active Cookie
Fetches a specific cookie object containing domain, value, path, and expiry metadata.
Cookie cookie = driver.manage().getCookieNamed("auth-token");Clear Browser LocalStorage
Wipes local web storage variables via JavaScript executor, commonly required for session cleanup.
((JavascriptExecutor) driver).executeScript("window.localStorage.clear();");Clear SessionStorage
Wipes volatile session storage variables to clear temporary client session states.
((JavascriptExecutor) driver).executeScript("window.sessionStorage.clear();");Capture Full-Page Screenshot
Captures a full visual image capture of the current active browser layout frame.
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);Capture Element Screenshot
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!
Switch to Active Element
Fetches the node holding document-focus, commonly used for tab navigation testing.
WebElement activeEl = driver.switchTo().activeElement();Retrieve Element Location in Viewport
Fetches screen coordinate offsets relative to the viewport layout.
Point point = element.getLocation();Wait for Alert Box presence
Explicit wait that pauses execution until a native browser alert is active and visible.
Alert alert = wait.until(ExpectedConditions.alertIsPresent());Emulate Geolocation via CDP DevTools
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)));Throttle Network Speed via CDP DevTools
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)));TestNG Before Method Hook
TestNG runner hook that executes before every individual test method. Perfect for driver setup.
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
}TestNG After Method Hook
TestNG runner hook that executes immediately after each test completes. Closes active windows.
@AfterMethod
public void tearDown() {
if (driver != null) driver.quit();
}TestNG Test Method Definition
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
}TestNG Parameter Injection
Injects environment and parameter inputs from testng.xml configurations.
@Parameters({"browser", "env"})
@BeforeClass
public void initConfig(String browser, String env) {
// cross-browser config
}TestNG DataProvider Injection
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" }
};
}Assertion - Check Equality
Hard assertion that compares strings, arrays, or objects and fails the test instantly on a mismatch.
Assert.assertEquals(actualText, expectedText, "Text verification failed!");Assertion - Check Condition
Hard assertion validating that a conditional expression evaluates to true.
Assert.assertTrue(element.isDisplayed(), "Element is not visible!");JUnit 5 Test Annotation
JUnit 5 standard runner annotation to execute test functions.
@Test
@DisplayName("Validate Checkout")
public void testCheckout() {
// junit 5 syntax
}Soft Assertion Initiation
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!
Verify Element Not Present
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!");PageFactory Model Initialization
Initializes Page Factory elements declared under @FindBy annotations in Page Objects.
PageFactory.initElements(driver, this);FindBy Selector Annotation
Declares element matching selectors inside Page Objects. Elements are lazily located on usage.
@FindBy(css = "input[data-testid='user-input']")
private WebElement usernameInput;Logger Output Info Message
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");Logger Output Error Message
Logs debug trace error points to files and reports when assertions or exceptions are thrown.
log.error("Exception occurred while completing flow: {}", e.getMessage());Read Framework Property Configurations
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");Write File Logger Output
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();Handle File Upload (SendKeys bypass)
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!
Verify Completed File Download
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();Shadow DOM SearchContext traversal
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"));Headless Browser Configuration
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");Configure Incognito Mode
Configures browser context execution to run in isolated Incognito / Private layout settings.
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");Selenium Grid RemoteWebDriver Setup
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);