Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

SessionNotFoundException means your screenshot command is reaching a WebDriver session that has already been deleted, changed, or detached. In the Internet Explorer incident that matches this error, a teardown method closed the browser before a JUnit screenshot rule ran. The accepted fix was to keep the same driver alive for the rule by moving setup and shutdown from @Before/@After to @BeforeClass/@AfterClass. Fix that lifecycle ordering first; only then investigate IE configuration and synchronization.

What the exception actually means

TakesScreenshot#getScreenshotAs does not create a new browser. It sends a command containing the current WebDriver session ID to InternetExplorerDriver. Selenium documents that this error usually appears after the session was deleted (for example, by driver.quit()) or after the last tab was closed (for example, by driver.close()). A bad filename or image format is therefore not the first suspect.

  • Dead session: a teardown, test utility, or application code called quit(), or closed the final window.
  • Changed session: the helper is using a different, stale driver object or a session that was recreated elsewhere.
  • Driver/browser disconnect: Internet Explorer or IEDriverServer exited, hung, or lost its attachment.
  • Timing failure: the browser is alive but the page is not in the state your test expects. Selenium identifies poor synchronization as a common source of WebDriver errors; it can obscure the real lifecycle problem.

Fix teardown ordering before changing IE settings

Screenshot failure handling must run while the browser session still exists. In JUnit 4, a per-test @After method can execute before a rule that captures the failure image, depending on how the rule and teardown are arranged. The matching report found that a close event occurred before the screenshot rule. Its solution kept the driver for the class lifetime.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Lifecycle pattern that keeps the session available

public class IeUiTest {
    private static WebDriver driver;

    @BeforeClass
    public static void startBrowser() {
        driver = new InternetExplorerDriver();
    }

    @Rule
    public TestWatcher screenshotOnFailure = new TestWatcher() {
        @Override
        protected void failed(Throwable error, Description description) {
            captureFailure(description.getMethodName());
        }
    };

    @AfterClass
    public static void stopBrowser() {
        if (driver != null) {
            driver.quit();
            driver = null;
        }
    }

    private static void captureFailure(String testName) {
        if (driver == null) {
            System.err.println("No WebDriver instance; screenshot unavailable");
            return;
        }
        try {
            System.out.println("Session: " + driver.getWindowHandle());
            System.out.println("Windows: " + driver.getWindowHandles());
            File source = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            Path target = Paths.get("target", "screenshots", testName + ".png");
            Files.createDirectories(target.getParent());
            Files.copy(source.toPath(), target, StandardCopyOption.REPLACE_EXISTING);
        } catch (SessionNotFoundException e) {
            System.err.println("The IE session ended before capture: " + e.getMessage());
        } catch (WebDriverException | IOException e) {
            System.err.println("Could not save failure screenshot: " + e.getMessage());
        }
    }
}

Adapt the watcher to your existing JUnit rule or reporting library. The important properties are not the class names: one driver instance is created before the tests, the failure hook uses that exact instance, and quit() runs only after capture has had a chance to finish.

If you need one browser per test

You can still use @Before/@After, but the screenshot callback must run before the @After method closes the browser. If your framework does not guarantee that ordering, move the capture into the failure hook itself or use a framework extension with an explicit “after test, before teardown” phase. Never call driver.quit() from a page object, assertion helper, or generic error handler that can run before the hook.

Use one live driver instance

A common variation is creating a driver in the test class and another in a screenshot helper. The helper’s object may have no session, while the test’s browser is still visible. Pass the original instance directly or store it in one controlled fixture. Do not “repair” a failed capture by constructing a second driver inside the failure callback: that produces a screenshot of a new blank session, not the failed state.

Check the session immediately before capture

  1. Confirm the driver reference is non-null.
  2. Call getWindowHandles() and record the result. An empty set or a thrown exception indicates that the session is gone.
  3. Capture immediately; do not perform navigation, long waits, or cleanup first.
  4. If the session has ended, record the failure and recreate it for subsequent tests. The original failure screenshot cannot be recovered.

Checking a handle is diagnostic, not a guarantee: the browser can exit between the check and getScreenshotAs. Keep the operation close together and log the first exception.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate synchronization failures from session loss

When IE is open but a page is still loading, use an explicit wait for the state you need rather than a fixed sleep. For example:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("results")));
File image = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

Choose a condition that represents your page: an element visible, a URL reached, or a loading indicator removed. If the wait times out, capture while the session is still alive and report both the timeout and the screenshot result. Compare the same test in another browser. If only IE loses the session, investigate IEDriverServer and IE configuration; if every browser fails at the same teardown point, fix the test lifecycle.

Internet Explorer configuration that can disconnect the driver

Match Protected Mode in every security zone

Selenium’s IE guidance requires Protected Mode to have the same setting in every Internet Explorer security zone. A mismatch can prevent reliable native automation. The preferred remedy is to make the zone settings consistent. The capability ignoreProtectedModeSettings bypasses Selenium’s check, but Selenium warns that doing so can make tests flaky, unresponsive, or hang; treat it as a diagnostic fallback rather than a normal fix.

Set browser zoom to 100 percent

InternetExplorerDriver’s native coordinate calculations expect 100% zoom. Set the browser zoom to 100% on the test machine and keep it there. A non-default zoom can cause clicks and element coordinates to miss, producing secondary failures that look like timing or driver instability.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Apply the IE11 BFCACHE setting when required

For IE11, Selenium’s documented configuration may require the registry value FEATURE_BFCACHEiexplore.exe as a DWORD set to 0. Apply registry changes through your organization’s approved Windows process, restart IE, and verify the setting on the machine that runs the tests. This setting helps the driver maintain its connection; it does not fix a test that calls quit() before the screenshot.

Make IEDriverServer discoverable

Put IEDriverServer.exe on PATH, or set the webdriver.ie.driver system property to its full path before constructing InternetExplorerDriver. A missing or mismatched executable normally fails at startup, but the exact driver and browser versions should still be recorded in your test log.

Avoid unsupported Windows Service execution

Selenium’s IE Driver Server documentation says running IEDriverServer.exe under a Windows Service is unsupported and untested. Run it in an interactive session on a configured desktop instead. Service isolation can otherwise make IE exit or behave differently from an interactive run.

Clean sessions and private mode: what they do and do not fix

Option Purpose Trade-off
ie.ensureCleanSession=true Clears cache, history, and cookies for all running IE instances before starting. Slower startup; disabled by default. It does not keep a prematurely closed session alive.
ie.forceCreateProcessApi=true plus ie.browserCommandLineSwitches=-private Starts IE in private mode to reduce shared session data. Addresses isolation, not teardown ordering or a lost driver connection.
ignoreProtectedModeSettings Bypasses the Protected Mode consistency check. Selenium warns of possible flakiness, unresponsiveness, or hangs.

Use these capabilities only when the symptom matches their purpose. Adding every option can increase startup time and hide the original defect.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Turn on IE driver logging

Configure IEDriverServer’s log file and an appropriate level—FATAL, ERROR, WARN, INFO, DEBUG, or TRACE. Correlate the timestamp of the screenshot call with messages showing IE exit, a lost attachment, navigation failure, or an explicit close. Preserve the test name, process identity, browser version, driver version, window handles, and the first WebDriver exception. Logs often distinguish “the test called quit()” from “IE crashed before the call.”

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common symptoms and targeted fixes

  • Exception appears only in failure screenshots: teardown is closing the last window first. Reorder the hook or use class-level setup and teardown.
  • Exception appears after a page object method: search helpers and page objects for hidden close()/quit() calls; centralize ownership in the fixture.
  • Browser is visible but the helper reports no session: the helper has a different driver instance. Pass the fixture’s instance.
  • Every test loses IE after navigation: verify Protected Mode, 100% zoom, IE11 BFCACHE, and driver logs; then compare another browser.
  • Startup became very slow after a change: disable ensureCleanSession unless clearing shared data is required.
  • Capture occasionally hangs: inspect synchronization and IE driver logs; do not hide it with ignoreProtectedModeSettings without accepting its documented risk.
  • Augmenter throws a CGLIB IllegalAccessException: augmentation is not the fix for this incident. Correct lifecycle ordering and use the native TakesScreenshot interface.

Or skip the browser setup

When you need a URL image rather than a live IE test state, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

cURL (see the ScreenshotNeo documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The service also supports full-page lazy-image capture, CSS-element shots, device presets and custom viewports, retina scale, PDF output, custom CSS or JavaScript, clicks, selector/delay/network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous webhooks, bulk calls for 100 URLs, usage reporting, and an OpenAPI specification. Every feature is on every plan: 1,000 shots per month are free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Cost, reliability, and evidence handling

A native IE screenshot is tied to the health of a desktop browser, its driver process, Windows security-zone settings, and test teardown. Keep the capture path short, log failures, and treat a missing image as a separate artifact failure rather than replacing the original assertion. For URL-based captures, check X-Page-Verdict and X-Billed headers so automation can distinguish a clean billed image from a blocked, blank, timed-out, failed, or cached response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I recover a screenshot after InternetExplorerDriver has quit?

No. Once the WebDriver session is deleted, the driver cannot capture its former browser state. Recreate the session for later tests and report the original image as unavailable.

Does SessionNotFoundException mean the PNG path is wrong?

Usually not. It identifies a missing or changed WebDriver session; file-path and encoding errors occur after a live session has produced image data.

Should I replace Internet Explorer with another browser?

Use another supported browser when your application no longer requires IE, but first verify whether the failure is your teardown order. A cross-browser run is useful for separating a test-lifecycle defect from an IE-specific driver problem.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.