driver.close() terminates the test - java

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

Related

How to handle keyboard operation on selenium chrome browser running on virtual ubuntu 22

I am trying to select "OK" button against my browser certificate pop-up using robot class. The same piece of code works well on windows but failing on ubuntu.
Code:
public void load() {
setUrl();
Thread threadNavigation = new Thread() {
#Override
public void run() {
driver.navigate().to(url);
}
};
Thread threadCertificateHandler = new Thread() {
#Override
public void run() {
try {
Thread.sleep(3000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(2000);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Start the threads.
threadNavigation.start();
threadCertificateHandler.start();
// Wait for them both to finish
try {
threadNavigation.join();
threadCertificateHandler.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Code Explanation: As soon as url is navigated using selenium, a certificate pop-up is displayed before page is loaded. The approach I have used here - 1 thread used here to get application url and another thread is used to handle the pop-up.
Attaching screenshot of the pop-up.
ChromeDriver Init Code:
public void getStandaloneHubNodeServerDriver(String browserType,String platformType, String url) throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
logger.log(Level.INFO, () -> "Setting browser address #: " + url);
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
options.setAcceptInsecureCerts(true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
//threadLocalDriver.set(new RemoteWebDriver(new URL(url),options));
driver = new RemoteWebDriver(new URL(url),options);
driver.manage().window().maximize();
}
The same code works like a charm on local windows but when executed on remote VM running on linux, it does not perform the "Enter" event. Is there's any alternative to Robot class that can be used for linux?
Robot class is generally inconsistent as it blindly performs keyboard or mouse actions. I have figured out a solution to select the browser certificate without Robot class. This works only on Firefox though. If you are happy to switch from Chrome to Firefox, try the below code:
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-profile");
options.addArguments("C:/Users/username/AppData/Roaming/Mozilla/Firefox/Profiles/zyz.default");
WebDriver driver = new FirefoxDriver(options);
In the above code, driver instance is loaded with the default Firefox browser profile. This profile will contain the certificate which will be accepted automatically and pop-up will not even be triggered. Try this and see if you can get away from using Robot class.

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.

How to close child browser window in Selenium WebDriver using 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 ");
}
}

Categories