Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Seimone Avatar asked Jun 07 '16 03:06

Seimone


2 Answers

Why not just:

driver.quit()
driver = new ChromeDriver()

What is your scenario really?

like image 182
Riaz Avatar answered Sep 28 '22 01:09

Riaz


@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.
like image 28
Ashok kumar Ganesan Avatar answered Sep 28 '22 02:09

Ashok kumar Ganesan