1

Without using the driver.close() the webdriver closes the browser window in Selenium 4. I want the browser to remain opened until I say driver.close().

After executing my code the Selenium Webdriver should not close the browser. The web browser should be opened until I call the driver.close() or driver.quit(). Is there any option to keep the browser opened. I am using Selenium 4 with Java 17.

import java.time.Duration;
import org.openqa.selenium.WebDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

public class CloseBrowserTest_1
{
    static WebDriver driver = null;

    public static void main(String[] args) throws InterruptedException
    {
        driver = WebDriverManager.chromedriver().create();      
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));   
        driver.manage().deleteAllCookies();
        
        driver.get("https://www.google.com");
        System.out.println("Title : " + driver.getTitle());
        System.out.println("Current URL : " + driver.getCurrentUrl());
    }
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190
asn
  • 11
  • 3

1 Answers1

1

There are some options on keeping the browser open after the last line of code. Not sure why would you use it, but hopefully this helps.

If you are waiting for an element or some action, you can always use wait. With that, your browser will stay open until the element you're waiting for has appeared or the wait timeout has expired (you define your own timeout duration). For more information visit this link

On the other hand, which I do not recommend, you can use Thread.sleep. It keeps the driver open, but in a sleep position. This method is not recommended though.

Funky Monkey
  • 121
  • 5
  • It sounds like the OP has a console mode Java program, and the webdriver closes when his program ends. As it should ;) SUGGESTION: Simply add \a[System.in.read()](https://stackoverflow.com/a/6032257/421195) at the end of `main()`. So the program won't exit until the user hits "ENTER". – paulsm4 Aug 27 '23 at 23:19
  • As per your suggestion, I have used System.in.read() as the last statement in the main(). The code worked as I expected. Thanks. – asn Aug 28 '23 at 04:10
  • @paulsm4 please add this as a definitive answer to the question, for others that may come across it – djmonki Aug 29 '23 at 06:12
  • @asn please accept answer, once paulsm4 has published it – djmonki Aug 29 '23 at 06:13