We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Capturing visual evidence and using JavaScript for tricky interactions in Selenium.
You’ll work with two key Selenium interfaces: TakesScreenshot for saving images and JavascriptExecutor for running JS code directly in the browser.
element.getScreenshotAs(...). Great for visual regression.executeScript("..."): Run custom JS.Scroll down to find the target...
This IS the box that will be captured as an image.
NormalUse scrollIntoView() to find the box, highlight it, and snap a picture!
1234567891011121314151617WebElement captureArea = driver.findElement(By.id("captureArea"));
// 1. Scroll into view and highlight using JavaScript
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", captureArea);
js.executeScript("arguments[0].style.border='5px solid red';", captureArea);
// 2. Take full-page screenshot
TakesScreenshot camera = (TakesScreenshot) driver;
File fullPageSrc = camera.getScreenshotAs(OutputType.FILE);
Files.copy(fullPageSrc.toPath(), Path.of("screenshot-fullpage.png"));
// 3. Take element-only screenshot
File elementSrc = captureArea.getScreenshotAs(OutputType.FILE);
Files.copy(elementSrc.toPath(), Path.of("screenshot-element.png"));
driver.quit();Integrate screenshot logic into a test listener so that failures automatically produce screenshots for your reports.
For visual regression or component-based checks, element.getScreenshotAs() is usually more stable than full-page shots.
Use consistent naming: include test name and timestamp in filenames.