WebDriver Commands and Browser Handling

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

close()quit()
closes the current window/tabcloses all windows and ends the session
the driver process keeps running if other windows are openstops the browser driver process
use after finishing with a popup windowuse in @AfterMethod teardown

Note: Calling close() on the last window and never quit() leaves chromedriver processes running on CI agents.

How do you handle multiple windows or tabs?

String parent = driver.getWindowHandle();
driver.findElement(By.linkText("Track Order")).click();          // opens a new tab

for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(parent)) driver.switchTo().window(handle);
}
System.out.println(driver.getTitle());                         // Track Order | ShopEase
driver.close();
driver.switchTo().window(parent);

// Selenium 4: open a new tab yourself
driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://shopease.example.com/help");

How do you handle alerts and iframes?

// JavaScript alert / confirm / prompt
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.alertIsPresent());
System.out.println(alert.getText());     // "Remove this item from cart?"
alert.accept();                          // OK  (alert.dismiss() = Cancel, alert.sendKeys("...") for prompt)

// iframe (e.g. payment widget)
driver.switchTo().frame("payment-frame");                  // by name/id, index or WebElement
driver.findElement(By.id("upi-id")).sendKeys("asha@okhdfc");
driver.switchTo().defaultContent();                         // back to the main page

Without switching you get NoSuchElementException, because the iframe has its own document.

How do you take a screenshot, run headless and use JavaScriptExecutor?

// screenshot of the page and of one element
File page = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File card = driver.findElement(By.cssSelector(".product-card")).getScreenshotAs(OutputType.FILE);

// headless Chrome
ChromeOptions options = new ChromeOptions().addArguments("--headless=new", "--window-size=1920,1080");

// JavaScriptExecutor: scroll, or click when an overlay blocks a normal click
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView({block:'center'});", element);
String title = (String) js.executeScript("return document.title;");

Tip: Use JavaScript clicks only as a last resort: they bypass what a real user can do, so they can hide real bugs (a button covered by a banner).