How to close child browser window in Selenium WebDriver using Java - java

After I switch to a new window and complete the task, I want to close that new window and switch to the old window,
so here i written like code:
// Perform the click operation that opens new window
String winHandleBefore = driver.getWindowHandle();
// Switch to new window opened
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
driver.findElement(By.id("edit-name")).clear();
WebElement userName = driver.findElement(By.id("edit-name"));
userName.clear();
try
{
driver.quit();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("not close");
}
driver.switchTo().window(winHandleBefore);// Again I want to start code this old window
Above I written code driver.quit() or driver.close(). But I am getting error. Can anybody help me...?
org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.

To close a single browser window:
driver.close();
To close all (parent+child) browser windows and end the whole session:
driver.quit();

The logic you've used for switching the control to popup is wrong
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
How the above logic will swtich the control to new window ?
Use below logic to switch the control to new window
// get all the window handles before the popup window appears
Set beforePopup = driver.getWindowHandles();
// click the link which creates the popup window
driver.findElement(by).click();
// get all the window handles after the popup window appears
Set afterPopup = driver.getWindowHandles();
// remove all the handles from before the popup window appears
afterPopup.removeAll(beforePopup);
// there should be only one window handle left
if(afterPopup.size() == 1) {
driver.switchTo().window((String)afterPopup.toArray()[0]);
}
// Perform the actions on new window
**`//Close the new window`**
driver.close();
//perform remain operations in main window
//close entire webDriver session
driver.quit();

//store instance of main window first using below code
String winHandleBefore = driver.getWindowHandle();
Perform the click operation that opens new window
//Switch to new window opened
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
driver.close(); //this will close new opened window
//switch back to main window using this code
driver.switchTo().window(winHandleBefore);
// perform operation then close and quit
driver.close();
driver.quit();

There are 2 ways to close the single child window:
Way 1:
driver.close();
Way 2: By using Ctrl+w keys from keyboard:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");

I've also tried
1)driver.close();
2)driver.quit();
apparently, these methods don't work as expected!(not saying it don't work though) I've even tried making the driver class singleton and it didn't help me with running test cases parallel.so it was also not the optimal solution.finally, i came up creating a separate class to run a bat file.which the bat file contains commands of grouping all the chrome driver process and all the child processes of it.and from the java class I've executed it using Runtime.
The class file that runs the bat file
public class KillChromeDrivers {
public static void main(String args[]) {
try {
Runtime.getRuntime().exec("cmd /c start E:\\Work_Folder\\SelTools\\KillDrivers.bat");
//Runtime.getRuntime().exec()
} catch (Exception ex) {
}
}
}
The command that you have to put in the [ .bat ] file
taskkill /IM "chromedriver.exe" /T /F

There are some instances where a window will close itself after a valid window handle has been obtained from getWindowHandle() or getWindowHandles().
There is even a possibility that a window will close itself while getWindowHandles() is running, unless you create some critical section type code (ie freeze the browser while running the test code, until all window management operations are complete)
A quicker way to check the validity of the current driver is to check the sessionId, which is made null by driver.close() or by the window closing itself.
The WebDriver needs to be cast to the remote driver interface (RemoteWebDriver) in order to obtain the sessionId, as follows:
if (null == ((RemoteWebDriver)driver).sessionId) {
// current window is closed, switch to another or quit
} else {
// current window is open, send commands or close
}
Also note that closing the last window is equivalent to quit().

public class First {
public static void main(String[] args) {
System.out.println("Welcome to Selenium");
WebDriver wd= new FirefoxDriver();
wd.manage().window().maximize();
wd.get("http://opensource.demo.orangehrmlive.com/");
wd.findElement(By.id("txtUsername")).sendKeys("Admin");
wd.findElement(By.id("txtPassword")).sendKeys("admin");
wd.findElement(By.id("btnLogin")).submit();
**wd.quit(); //--> this helps to close the web window automatically**
System.out.println("Tested Sucessfully ");
}
}

Related

How to handle multiple windows in selenium?

While automating via Selenium WebDriver, I have the below scenario. On a window, I copy the link and want to open the link on the new window(not in the new tab) and want to set focus on the new window. (Here the second window is not the child window of the first window)please help
You can do something like this
WebDriver driverOne=new ChromeDriver();
// navigate to your desired URL
driverOne.get("http://www.yourwebsite.com/");
// Do your stuff and copy the new link
// string newURL;
WebDriver driverSecond=new ChromeDriver();
driverSecond.get(newURL);
driverSecond will have a focus on the new window and once your actions are complete close the driverSecond.
In Selenium 4 (currently in beta), you the following will open a new window then automatically switch to the window:
#Test
public void openNewWindowForTestProjectBlog () {
WebDriver newWindow = driver.switchTo().newWindow(WindowType.WINDOW);
newWindow.get("https://blog.testproject.io/");
System.out.println(driver.getTitle());
}
//assume - multiple windows are opened by clicking link or a button.
Set<String> windows = driver.getWindowHandles();
for (String window : windows)
{
if (driver.getTitle().contains("***Something that is on new window***"))
{
driver.switchTo().window(window);
//To get title of new window
System.out.println(driver.switchTo().window(window).getTitle());
}
}

Getting difficulty to focus on newly open window in selenium

I am unable to focus on newly open window using selenium and java.
I am using Internet explorer for running my application.
The new window is opening but not able to perform anything on the new window.
I tried with
Set<String> allwindows = driver.getWindowHandles();
but still issue is not resolved.
Below is the code I am using .
driver.get("www.tririga.com");
String parentwindow=driver.getWindowHandle();
driver.findElement(By.id("login")).click();
for(String childwindow: driver.getWindowHandles()) {
driver.switchto().window(childwindow);
driver.findElement(By.id("submit")).click();
driver.close();
}
driver.switchto().window(parentwindow);
driver.close();
You need to check that you are not using the first window handle to switch. You can also wait for the new window to open with explicit wait
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.findElement(By.id("login")).click();
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
for(String childwindow: driver.getWindowHandles()) {
if (!childwindow.equals(parentwindow)) {
driver.switchto().window(childwindow);
driver.findElement(By.id("submit")).click();
driver.close();
}
}
driver.switchto().window(parentwindow);
driver.close();
If this is the end of your code and you just want to close all the windows just use quit()
Quits this driver, closing every associated window.
for(String childwindow: driver.getWindowHandles()) {
if (!childwindow.equals(parentwindow)) {
driver.switchto().window(childwindow);
driver.findElement(By.id("submit")).click();
}
}
driver.quit();

How to handle browser notification popup which is without any elements?

How to press the OK button as per the image.
I can switch to this window. but it is not loaded till i click ok, so there is no any elements.
Alert handle does't helped too.
Autoit cannot detect this pop up message too.
disable-notifications cant help too.
Any ideas?
Two screeshots is added.
Firefox snapshot:
Chrome Snapshot:
p.companieGenreal.sActivities().click();
driver.switchTo().defaultContent();
String parent = driver.getWindowHandle();
p.companieGenreal.sAddNew().click();
p.companieGenreal.sAddJobOrder().click();
p.companieGenreal.sContract().click();
swithToChildWindow(parent);
driver.switchTo().alert().accept();
To treat it as an alert try this:
Alert a = driver.switchTo().alert();
a.confirm();
If it can be closed with Escape key, send Escape keypress like this (or ENTER if it closes when Enter is hit):
Actions action = new Actions(driver);
action.sendKeys(Keys.ESCAPE);
beforeunload
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. At this point of time the document is still visible and the event is still cancelable.
Note: Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.
Solution
There are multiple ways to disable this popup as follows:
Firefox: If you are using Firefox as your Browser Client you can use an instance of FirefoxOptions() and set the preference dom.disable_beforeunload to true as follows:
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
FirefoxOptions firefox_option = new FirefoxOptions();
firefox_option.addPreference("dom.disable_beforeunload", true);
WebDriver firefox_driver = new FirefoxDriver(firefox_option);
firefox_driver.get("https://stackoverflow.com/");
Chrome: If you are using Chrome as your Browser Client you can use an instance of ChromeOptions() and add the argument --disable-popup-blocking as follows:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions chrome_option = new ChromeOptions();
chrome_option.addArguments("--disable-popup-blocking");
chrome_option.addArguments("start-maximized");
chrome_option.addArguments("disable-infobars");
WebDriver chrome_driver = new ChromeDriver(chrome_option);
chrome_driver.get("https://stackoverflow.com/");
try using this :
public static void acceptAlertUsingJs(WebDriver driver) {
((JavascriptExecutor)driver).executeScript("window.alert = function(msg){return true;};");
((JavascriptExecutor)driver).executeScript("window.prompt = function(msg) { return true; }");
((JavascriptExecutor)driver).executeScript("window.confirm = function(msg) { return true; }");
}
Please try the below code and see if it helps:
if (isAlertPresent()){
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
}
public static boolean isAlertPresent() {
try {
driver.switchTo().alert();
Thread.sleep(5000);
return true;
}// try
catch (Exception e) {
return false;
}// catch
}
I have the same kind of issue a modal pop up window opens to which i am able to switch to and click the OK button but cannot fetch the text present in it. The modal dialog is shared in the screenshot and has no html tags hence i cannot locate the text in it using any locator. I tried using driver.switchTo().alert().getText() to fetch the text present in it.
If that is an alert you could handle using below methods:
driver.switchTo().alert().accept();
"Actions class":
Actions builder=new Actions(driver);
builder.sendKeys(keys.ESCAPE);
if the above two methods didn't work then there is a special alert type called "sweet alert" which can be inspected and write code for that.

driver.close() terminates the test

I use selenium WebDriver. I am trying to run following scenario.
I launch a url, and I want to add a condition that if there is any url opened other than the one I intended, I want to close it.
Following is my code, I will explain whats happening with it below.
if (config.getProperty("browser").equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
selectServer();
String currentURL = driver.getCurrentUrl();
if (currentURL != config.getProperty("production") || currentURL != config.getProperty("staging") || currentURL != config.getProperty("development"))
{
Thread.Sleep(10000); //for Debugging purpose
driver.close();
}
}
I have a config.properties file where I set the browser / server selection.
Now what happens is, when I launch the test, chrome launches and:
Chrome settings window opens and it asks me to restore default settings. (Window in display)
My intended URL opens up. (hidden)
When I run the test, the test passes but Chrome Settings window does not close. I tried to print the current URL , and it returns the production server URL which is my intended URL but the browser window in display is not my production URL.
Based on your response in comments, I believe you need to switch to the settings tab, close that tab, then switch back to the original tab. The below code should do that:
public static void closeBrowserTab() {
String originalHandle = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
driver.switchTo().window(handle);
driver.close();
break;
}
}
driver.switchTo().window(originalHandle);
}

How to switch to existing window after closing the current window in Selenium Automation using java

Actually, i'm trying to switch the control from current window to existing window after closing the current one in Selenium Automation using java. Is there any way to do that. I'm able to control the newly opened window, doing some process & closing this one. Later i just need to move to already existing browser window.
This is something that I use , this checks for all the open windows and then switchess control to the next window with an option to close out the older window.
protected final void switchWindows(boolean closeOldWindow) {
final WebDriver driver = checkNotNull(getDriver(), "missing WebDriver");
final String currentWindow = driver.getWindowHandle();
checkNotNull(currentWindow);
// switch to first window that is not equal to the current window
String newWindow = null;
for (final String handle : driver.getWindowHandles()) {
if (!currentWindow.equals(handle)) {
newWindow = handle;
break;
}
}
// if there's another window found...
if (newWindow != null) {
if (closeOldWindow) {
// close the current window
driver.close();
}
// ...switch to the new window
driver.switchTo().window(newWindow);
}
}
I just know selenium js webdriver have a api like driver.switchTo().window(windowName) could help us move to another window. I am not so familiar with Java API but they are all from almost same invoking way. hope this would help you.
you can use this-
private void handleMultipleWindows(String windowTitle) {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
if (driver.getTitle().contains(windowTitle)) {
return;
}
}
}
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows
Once you closed the current window, you will be seeing the parent window.
To switch back to your parent/previous window you can use the following commands,
driver.getUIWindowLocator().switchToFirstWindow();
driver.switchTo().defaultContent();
commands. I think this will be helpful for you.
Please do following code for switching back to base window or original window.
String vBaseWindowHandle = driver.getWindowHandle();
Set<String> windows = driver.getWindowHandles();
for(String temp : windows)
{
driver.switchTo().window(temp);
}
// Do code for new window
driver.close();
driver.switchTo().window(vBaseWindowHandle);
For more information about how to handle Windows and popup in selenium please go to below URL.
https://trickyautomationworld.blogspot.in/2018/03/how-to-handle-windows-in-selenium.html
https://trickyautomationworld.blogspot.in/2018/03/how-to-handle-popup-in-selenium.html

Categories