Search code examples
javagoogle-chromeselenium-webdriverfirefoxwebdriver

Java Selenium WebDriver closes the web browser after reaching the last line of code?


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());
    }
}

Solution

  • 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.