intermediate19 min

File Upload, Cookies, and Screenshots

Uploading a real local file without a native OS dialog, reading and setting cookies directly, and capturing a screenshot for evidence — plus JavaScript execution's honest limits.

What you'll learn

  • Upload a file to a standard <input type='file'> without any OS-level file picker
  • Read and set cookies directly through WebDriver's cookie management API
  • Explain the honest limitation of driver.executeScript for verifying real user-facing behavior

Prerequisites

Explanation

Uploading a file with Selenium does not involve automating a native OS file-picker dialog at all — that dialog exists entirely outside the browser's DOM, in OS-level UI Selenium (and browser automation generally) cannot reach. Instead, driver.findElement(By.cssSelector("input[type='file']")).sendKeys("/absolute/path/to/file.txt") sets the file input's value directly, exactly as if a real file had been chosen — the browser handles the rest identically either way. This requires an absolute path to a real, existing local file (a relative path or a non-existent file silently fails or behaves unpredictably depending on the browser), which is worth stating precisely rather than leaving as a vague gotcha.

Cookies are readable and settable directly through WebDriver's cookie API, independent of any UI interaction: driver.manage().getCookies() returns every cookie for the current domain; driver.manage().addCookie(new Cookie("session", "abc123")) sets one directly; driver.manage().deleteAllCookies() clears them. This is genuinely useful for fast test setup — establishing a signed-in-looking state by setting a session cookie directly, when the application's cookie-based session mechanism allows it, is dramatically faster than clicking through a real login form for every single test, the same principle behind Playwright's storageState if you've encountered that pattern elsewhere, expressed through Selenium's own direct cookie API instead.

Screenshots (((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE)) capture the current viewport (or, with some driver/browser combinations, the full scrollable page) as evidence — most valuable captured automatically on test failure via a JUnit extension or @AfterEach hook checking the test's outcome, exactly the same principle as this course's earlier lesson on driver lifecycle. driver.executeScript(...) runs arbitrary JavaScript directly in the browser's page context, and it's a genuinely powerful escape hatch — but it comes with an honest limitation worth stating clearly: a value read via executeScript (checking a JavaScript variable, or reading element.value directly from the DOM) can diverge from what a real user actually experiences, since executeScript bypasses the same actionability/visibility checks a genuine click or keystroke goes through — a script-based check can report an element's value as "set" even if that element is actually hidden, disabled, or covered by an overlay a real user could never have interacted with. Using executeScript as a shortcut to skip real interaction, rather than for its legitimate, narrower use (scrolling, reading page-level state not reachable through the standard API) is a common way to accidentally test something other than genuine user-facing behavior.

Example

Modeling direct file-input assignment (no OS dialog) and the executeScript honesty gap, as data.

function uploadViaSendKeys(inputElement, absolutePath) {
  const looksAbsolute = absolutePath.startsWith("/") || /^[A-Za-z]:/.test(absolutePath);
  if (!looksAbsolute) {
    throw new Error("an absolute path is required -- relative paths behave unpredictably");
  }
  inputElement.value = absolutePath; // sets the file input directly -- no native OS dialog involved
  return "uploaded: " + absolutePath;
}
console.log(uploadViaSendKeys({}, "/home/user/resume.pdf")); // "uploaded: /home/user/resume.pdf"

function checksRealUserVisibility(method) {
  // executeScript bypasses the same actionability checks a real click/keystroke goes through.
  return method !== "executeScript";
}
console.log(checksRealUserVisibility("click"));         // true -- a real click checks visibility/enabled/etc.
console.log(checksRealUserVisibility("executeScript"));  // false -- can report state a real user could never have set

Try it yourself

Call uploadViaSendKeys with a RELATIVE path (e.g. 'resume.pdf') and confirm it correctly throws.

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Guided exercise

Guided exercise

Write buildCookie(name, value, domain) returning an object {name, value, domain} -- modeling new Cookie(name, value) with a domain set. Then write hasSessionCookie(cookies, cookieName) returning true if any cookie in the array has that exact name.

Checks: builds a correct cookie object · finds an existing cookie by name · correctly reports no match for an empty cookie list

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Stuck? Get a hint.

Independent exercise

Independent exercise

Write isTrustworthyCheck(method) modeling this lesson's honesty distinction: return true for 'click', 'sendKeys', or 'isDisplayed' (real interaction/visibility checks going through actionability), false for 'executeScript' (bypasses those checks -- can report state a real user could never have produced).

Checks: recognizes a real click as trustworthy · recognizes a real visibility check as trustworthy · recognizes executeScript as not equally trustworthy for user-facing verification

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Stuck? Get a hint.

Common mistakes

  • Trying to automate a native OS file-picker dialog -- Selenium cannot reach OS-level UI at all; sendKeys(absolutePath) on the file input directly is the correct, and only, approach.
  • Using a relative file path with sendKeys for file upload -- this behaves unpredictably across browsers/OSes; always use a real, absolute path to a file that genuinely exists.
  • Using executeScript to check or set a value as a shortcut, then treating that as proof a real user could achieve the same result -- executeScript bypasses the same actionability checks a real click or keystroke goes through, so it can report state a real user interaction could never have produced.

Knowledge check

Knowledge check

1. How does sendKeys(absolutePath) on an <input type='file'> element actually work?
2. Why is directly setting a session cookie via driver.manage().addCookie(...) often faster than logging in through the UI for every test?
3. What is the honest limitation of using driver.executeScript(...) to verify an element's value or visibility?

Takeaway

File upload sets the file input directly with no native OS dialog involved, requiring a real absolute path; cookies can be read/set directly for fast test setup; and executeScript, while a powerful escape hatch, bypasses real actionability checks, so using it as a shortcut for genuine interaction can report success a real user could never actually achieve.

Summary

sendKeys(absolutePath) on a file input uploads directly, no OS dialog involved -- the path must be absolute and real. Cookies are readable/settable directly via driver.manage(), useful for fast test setup. Screenshots capture evidence, ideally automatically on failure. executeScript bypasses real actionability checks, making it an honest but limited tool for verifying genuine user-facing behavior.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.