Skip to main content
← TesterRank/Automation Cheatsheet
← All CheatsheetsSelenium 4 • Java & Playwright Syntax

Selenium WebDriver Commands Cheatsheet

The definitive copy-paste reference guide for QA Automation Engineers and SDETs. Browser actions, element queries, Select dropdowns, Actions class mouse interactions, JavascriptExecutor, and multi-window handling.

How to Use This Commands Reference

This cheatsheet provides side-by-side syntax for Selenium WebDriver (Java) and modern Playwright. All commands are organized by functional domain. You can copy the code directly into your test suites or Page Object classes.

Selenium 4.25+W3C WebDriver CompliantPlaywright Compatible

1. Browser Actions

Navigate, resize, and control the browser

ActionSelenium JavaPlaywright
Open URL
driver.get("https://www.testerrank.com/banking")
page.goto("https://www.testerrank.com/banking")
Navigate to URL
driver.navigate().to("https://www.testerrank.com/shopping")
page.goto("https://www.testerrank.com/shopping")
Go back
driver.navigate().back()
page.goBack()
Go forward
driver.navigate().forward()
page.goForward()
Refresh page
driver.navigate().refresh()
page.reload()
Maximize window
driver.manage().window().maximize()
// Set in browser context config
Set window size
driver.manage().window().setSize(new Dimension(1920, 1080))
// Set viewport in browser.newContext()
Get page title
driver.getTitle()
page.title()
Get current URL
driver.getCurrentUrl()
page.url()
Close current tab
driver.close()
page.close()
Quit browser
driver.quit()
browser.close()

2. Element Actions

Click, type, read, and check element state

ActionSelenium JavaPlaywright
Click element
driver.findElement(By.id("loginBtn")).click()
page.locator("#loginBtn").click()
Type text
driver.findElement(By.id("userId")).sendKeys("testuser")
page.locator("#userId").fill("testuser")
Clear field
driver.findElement(By.id("userId")).clear()
page.locator("#userId").clear()
Get text
driver.findElement(By.id("welcomeUser")).getText()
page.locator("#welcomeUser").textContent()
Get attribute
driver.findElement(By.id("userId")).getAttribute("placeholder")
page.locator("#userId").getAttribute("placeholder")
Is displayed?
driver.findElement(By.id("errorMsg")).isDisplayed()
page.locator("#errorMsg").isVisible()
Is enabled?
driver.findElement(By.id("submitBtn")).isEnabled()
page.locator("#submitBtn").isEnabled()
Is selected?
driver.findElement(By.id("rememberMe")).isSelected()
page.locator("#rememberMe").isChecked()
Submit form
driver.findElement(By.id("loginForm")).submit()
// Use click on submit button instead
Press Enter key
driver.findElement(By.id("search")).sendKeys(Keys.ENTER)
page.locator("#search").press("Enter")

4. Alerts & Dialogs

Handle JavaScript alerts, confirms, and prompts

ActionSelenium JavaPlaywright
Accept alert (OK)
driver.switchTo().alert().accept()
page.on("dialog", d => d.accept())
Dismiss alert (Cancel)
driver.switchTo().alert().dismiss()
page.on("dialog", d => d.dismiss())
Get alert text
driver.switchTo().alert().getText()
page.on("dialog", d => console.log(d.message()))
Type in prompt
driver.switchTo().alert().sendKeys("my input")
page.on("dialog", d => d.accept("my input"))

5. Frames & iFrames

Switch context to and from frames

ActionSelenium JavaPlaywright
Switch by index
driver.switchTo().frame(0)
page.frameLocator("iframe").first()
Switch by name/ID
driver.switchTo().frame("frameName")
page.frameLocator("#frameName")
Switch by element
driver.switchTo().frame(driver.findElement(By.tagName("iframe")))
page.frameLocator("iframe")
Back to main page
driver.switchTo().defaultContent()
// Playwright auto-scopes via frameLocator
Back to parent frame
driver.switchTo().parentFrame()
// Not needed — use parent page locator

6. Windows & Tabs

Handle multiple browser windows or tabs

ActionSelenium JavaPlaywright
Get current window handle
String mainWindow = driver.getWindowHandle()
// Playwright uses page objects directly
Get all window handles
Set<String> handles = driver.getWindowHandles()
context.pages()
Switch to new window
driver.switchTo().window(handle)
const newPage = await context.waitForEvent("page")
Open new tab
driver.switchTo().newWindow(WindowType.TAB)
const newPage = await context.newPage()
Close & switch back
driver.close(); driver.switchTo().window(mainWindow)
newPage.close()

7. Screenshots

Capture page or element screenshots

ActionSelenium JavaPlaywright
Full page screenshot
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("screenshot.png"))
page.screenshot({ path: "screenshot.png", fullPage: true })
Element screenshot
driver.findElement(By.id("dashboard")).getScreenshotAs(OutputType.FILE)
page.locator("#dashboard").screenshot({ path: "element.png" })
Screenshot as bytes
byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)
const buffer = await page.screenshot()

8. JavaScript Executor

Execute JavaScript in the browser context

ActionSelenium JavaPlaywright
Scroll to element
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true)", element)
page.locator("#element").scrollIntoViewIfNeeded()
Click via JS
((JavascriptExecutor) driver).executeScript("arguments[0].click()", element)
page.locator("#element").click({ force: true })
Get page title via JS
((JavascriptExecutor) driver).executeScript("return document.title")
page.evaluate(() => document.title)
Scroll to bottom
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)")
page.evaluate(() => window.scrollTo(0, document.body.scrollHeight))
Highlight element
((JavascriptExecutor) driver).executeScript("arguments[0].style.border='3px solid red'", element)
page.locator("#el").evaluate(e => e.style.border = "3px solid red")

Advanced JavascriptExecutor Recipes

When native WebDriver commands are blocked by CSS animations, floating sticky bars, or complex shadow boundaries, leverage JavascriptExecutor to dispatch commands directly into the browser's JavaScript context:

JavascriptExecutorSnippets.javaJava
JavascriptExecutor js = (JavascriptExecutor) driver;

// 1. Force-click an element hidden behind a sticky header or overlay
js.executeScript("arguments[0].click();", hiddenButton);

// 2. Scroll element into the exact vertical center of the viewport
js.executeScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", targetElement);

// 3. Scroll to the very bottom of an infinite-scroll page
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

// 4. Retrieve value of a shadow DOM element
WebElement shadowHost = driver.findElement(By.id("shadow-host"));
WebElement shadowElement = (WebElement) js.executeScript(
    "return arguments[0].shadowRoot.querySelector('#inner-btn');", shadowHost);

// 5. Highlight an element with a red border during local debugging
js.executeScript("arguments[0].style.border='3px solid red';", targetElement);

Actions Class: Complex Mouse & Keyboard Sequences

For interactions beyond simple clicks — such as hovering over navigation menus, drag-and-drop file cards, and keyboard shortcuts — instantiate Selenium's Actions class:

ActionsClassExamples.javaJava
import org.openqa.selenium.interactions.Actions;

Actions actions = new Actions(driver);

// 1. Hover over navigation dropdown menu
actions.moveToElement(navbarMenu).perform();

// 2. Drag and drop a card from column A to column B
actions.dragAndDrop(sourceCard, destinationColumn).perform();

// 3. Right-click (Context Click) to open custom context menu
actions.contextClick(targetFileItem).perform();

// 4. Double-click to edit an inline text cell
actions.doubleClick(editableTableRow).perform();

// 5. Keyboard combination: Select all text and delete (Ctrl+A / Cmd+A + Backspace)
actions.click(inputField)
       .keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL)
       .sendKeys(Keys.BACK_SPACE)
       .perform();

Frequently Asked Questions (FAQ)

What is the difference between driver.close() and driver.quit() in Selenium?

driver.close() closes the currently focused browser window or tab. If other windows remain open, the WebDriver session and ChromeDriver OS process continue running in the background. driver.quit() closes all open windows, terminates the entire WebDriver session, and safely kills the browser driver background process. In automated test frameworks, always invoke driver.quit() inside the @AfterMethod or @AfterTest teardown to prevent memory leaks in CI runners.

How do you handle custom dropdowns that do not use HTML <select> tags?

Selenium's Select class only works on native HTML <select> elements. Modern web applications (React, Angular, Material UI) render dropdowns using <div>, <ul>, and <li> elements. To automate custom dropdowns: 1) Click the dropdown trigger element using By.cssSelector or By.xpath, 2) Use WebDriverWait with ExpectedConditions.visibilityOfElementLocated to wait for the dropdown options menu to open, and 3) Click the specific option element matching your desired text.

When should you use JavascriptExecutor over native WebElement click()?

Use native element.click() by default because it simulates real human user events (firing mousedown, mouseup, click, and triggering actionability checks). However, if an element is obscured by a floating header, disabled temporarily, or outside the visible viewport resulting in ElementClickInterceptedException, you can use JavascriptExecutor: ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element) to dispatch a direct DOM click event as a fallback.

How do you switch between multiple browser windows or tabs in Selenium 4?

In Selenium 4, you can open a new tab directly using driver.switchTo().newWindow(WindowType.TAB) or a new window with WindowType.WINDOW. To switch between existing tabs, capture the parent window handle via driver.getWindowHandle(), retrieve all active handles via driver.getWindowHandles(), iterate through the set, and switch to the handle that does not match the parent: driver.switchTo().window(childHandle). After completing your checks, close the child tab and switch back to the parent handle.

Practice These Commands Live

Test your Selenium commands against 10 real-world practice applications: banking, e-commerce, insurance, and travel sandboxes.