How can i close all idle web browsers opened by selenium?

How can i close all idle web browsers opened by selenium?

I am using "selenium-java.jar" file to open chrome headless drivers. Now we are using threads to open headless chrome. Now what happens if there is any error then sometime threads quits without closing browser.

So i want to implement a solution that if any headless chrome is ideal for last 20 minutes then close/quit it.

I searched on google and i found may solution which is around selenium server standalone like this https://github.com/seleniumhq/selenium/issues/1106

My problem is i cannot switch to standalone server now so i have to figure out solution with current library.

So is there any way to close all headless chrome browsers which are idle for last 20 minutes?

Please guide.


I use selenium-java.jar with TestNg and whilst I don't run headless browsers I do clean up after a test run in the TestNg aftermethod, which is not quite the same as your 20 min wait, but might be of help.

When running tests on a windows OS I check for to see if the process is running by name and terminate it:

public final class OsUtils
{
    private static final String TASKLIST = "tasklist";
    private static final String KILL = "taskkill /F /IM ";
    public static final String  IE_EXE = "iexplore.exe";
    public static final String  CHROME_EXE = "chrome.exe";
    public static final String  EDGE_EXE = "MicrosoftEdge.exe";
    public static final String  FIREFOX_EXE = "firefox.exe";


public static boolean isProcessRunning(String processName)
{
    Process process;
    try
    {
        process = Runtime.getRuntime().exec(TASKLIST);
    }
    catch (IOException ex)
    {
        Logger.error("Error on get runtime" + ex.getMessage());
        return false;
    }

    String line;
    try ( BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); )
    {
        while ((line = reader.readLine()) != null) {
            if (line.contains(processName)) {
                Logger.log("Process found");
                return true;
            }
        }
    }
    catch (IOException ex)
    {
        Logger.error("Error on check for process " + processName + ": " + ex.getMessage());
    }
    return false;
}

public static void killProcessIfRunning(String processName)
{
    Logger.log("Trying to kill process: " + processName);
    try
    {
        if (isProcessRunning(processName))
        {
            Runtime.getRuntime().exec(KILL + processName);
        }
    }
    catch (IOException ex)
    {
        Logger.error("Error on kill process " + processName+ ": " +  ex.getMessage());
    }
}
...
}

When running Safari on macmini I have a similar kill command (which works for both Safari proper and also the technology preview):

public static void killSafariProcess()
{
    Logger.log("Trying to kill Safari processes if running.");

    try
    {
        Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ps ux | grep -i app/Contents/MacOs/Safari | grep -v grep | awk '{print $2}' | xargs kill -9"});
    }
    catch (IOException ex)
    {
        Logger.error("Error on kill Safari processes: " +  ex.getMessage());
    }
}

The custom Logger class just uses System.out.println(message)

driver.close () and driver.quit () are 2 totally different ways for closing the browser session in Selenium WebDriver. Understanding both of them and knowing when to use which method is important in your test execution. driver.close () – It closes the current browser window on which the focus is set.


You could subclass ChromeDriver and implement your own proxy class with a timer to quit after 20 minutes idle time:

public class TimedChromeDriver extends ChromeDriver {

  Timer timeOut;

  private void initTimer() {
    timeOut = new Timer();
  }

  private void startTimer() {
    timeOut.cancel();
    timeOut.schedule(
        new TimerTask() {
          @Override
          public void run() {
            quit();
          }
        },
        20 * 60 * 1000);
  }

  public TimedChromeDriver() {
    initTimer();
  }

  @Override
  public void get(String url) {
    super.get(url);
    startTimer();
  }

  // override every method of WebDriver and ChromeDriver in the same way
}

This will only work if your Java VM is not terminated before the timer is triggered. The garbage collector could also interfere. Overriding the finalize method is deprecated.

I would invest some analysis effort into your threads quitting ungracefully. This would solve your problems at the source.

I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time - in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.


You can probably do some analysis on the start time of the different processes that match your driver criteria. I don't think it's going to tell you how long it's been idle, but you can probably assume that if it's been running for 20 mins (assuming your test should successfully complete within minutes) that it's probably orphaned.

I found this answer that shows how you can use Java to get a list of processes and see their start time. From there you should be able to find all of the drivers that are old and kill them.

An alternative might be to use Powershell to get the processes, start time, and deal with it in that way. It just depends on what you are looking for. Here's an answer to get you started down this path.

driver.close() and driver.quit() are two different methods for closing the browser session in Selenium WebDriver. driver.close() - It closes the the browser window on which the focus is set. driver.quit() – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.


Just as a complement for Julien Herr answer, you can use @AfterClass(alwaysRun = true) too. In my project I prefer AfterClass because this way I can run all tests of a class in a single instance of the browser instead of opening and closing for each test.


If the browser context is not handled and found no parent/main context then It will close all browsers. web elements specified in the Selenium all cookies related to the opened browser,


close () close () is a webdriver command which closes the browser window which is currently in focus. During the automation process, if there are more than one browser window opened, then the close () command will close only the current browser window which is having focus at that time. The remaining browser windows will not be closed.