How can Selenium close Chrome browser and open new One

My scenario is to close the chrome browser and open a new one.

public String openNewBrowserWindow() {
    this.log("Opening new Browser window...");
    String stringHandles;
    Set<String> previousWindows = driver.getWindowHandles();
    String previousHandle = driver.getWindowHandle();
    ((JavascriptExecutor)driver).executeScript("window.open();");
    Set<String> newWindows = driver.getWindowHandles();
    newWindows.removeAll(previousWindows);
    String newHandle = ((String)newWindows.toArray()[0]);
    stringHandles = previousHandle + ";" + newHandle;
    return stringHandles;
}

What I did is this:

String handlesA = generic.openNewBrowserWindow();
String[] handleA = handlesA.split(";");
generic.closeBrowser();
generic.switchToWindow(handleA[1]);

This works on firefox but not in chrome. Do you guys have any suggestion?


Solution 1:

Why not just:

driver.quit()
driver = new ChromeDriver()

What is your scenario really?

Solution 2:

@Seimone Whenever you want to intiate a Chrome browser, system property must be defined to the chromedriver.exe

System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
WebDriver driver = new ChromeDriver();

Also, If you want to close your current chrome browser window use the following one in your code.

driver.close();

If you want to close all your chrome browser window use the following one in your code.

driver.quit();

With reference to your scenario

  1. Open the url

  2. Login with signed in

  3. Close the browser

  4. Open the browser and enter the same url

  5. Check the same user is logged in

Try the below code and let me know your result.

String chromeDriver = "enter the chromedriver.exe path";
String chromeProfile = "C:/Users/MSTEMP/AppData/Local/Google/Chrome/User Data/Default"; //Local chrome profile path.
System.setProperty("webdriver.chrome.driver", chromeDriver);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("user-data-dir="+chromeProfile);
capabilities.setCapability("chrome.binary",chromeDriver);
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
WebDriver driver = new ChromeDriver(capabilities);

driver.get("https://www.gmail.com");
/*write your login credentials code with username, password and perform the
login operation with signed in*/
driver.close();

//Now invoke the chrome browser and enter the url alone.
driver = new ChromeDriver(capabilities);
driver.get("http://www.gmail.com");
//write the code for user signed verification.