Handling alerts in Selenium - java

I have a scenario in which clicking on "Save" button can give three different alerts based on the data entered. It can give "Saved successfully", "User already registered" and "Username already exist" alerts. I have tried:
driver.findElement(By.id("dnn_ctr5995_View_btnsavesession")).click();
Thread.sleep(10000);
Alert alert = driver.switchTo().alert();
String A = alert.getText();
if (A == "Username already exist"){
System.out.println("Admission number already exist.");
alert.accept();
} else if (A == "User already registered"){
System.out.println("User already registered");
alert.accept();
} else if (A == "Saved Successfully."){
System.out.println("Saved Successfully.");
alert.accept();
}
But it is showing No Alert present exception. I have tried increasing the sleep time but still it shows the same exception.

I'm guessing you never actually call alert.accept() because you're using A == "User already registered" instead of "User already registered".equalsIgnoreCase(A). If you change the if conditions, that should fix your problem.

As per the Html shared, the id of the element is not "save". So the first line of the shared code should be modified a bit to achieve the output.
Change the element identification tag to :
driver.findElement(By.id("dnn_ctr5995_View_btnsavesession")).click();
or if the 'id' of the element is changing on every instance, then it can be changed to:
driver.findElement(By.xpath("//*[contains(#id,'_View_btnsavesession')]")).click();

Looks like your clicking is not actually clicking because the 'save' id is no like in the element.
Try to do it like this:
driver.findElement(By.cssSelector("[id*=save"])).click();
And then trying to catch the alert. Please note the '*' in selector.

Related

Selenium WebDriver Java - how to perform "if exists, then click, else skip"?

On my page, I have alerts that display sometimes. (these are actually notifications in Salesforce) These alerts break my scripts since my scripts can't find the elements behind the alerts. I'd like to check for the alerts and if they exist, dismiss them. If they don't exist, then move on to the next step.
Secondary problem is that there may be more than one of these alerts. So it may have dismiss anywhere from 1 to 6 or more alerts.
I've added this code to my test script and it works if there is ONE alert. Obviously my script fails if there is more than one alert or if there are zero alerts.
driver.findElement(By.xpath("//button[contains(#title,'Dismiss notification')]")).click();
I'm still learning java, so please be gentle. ;) But I'd love to put this into a method so it can look for those buttons, click if they exist, keep looking for more until it finds none, then move on. I just have no idea how to do it.
I'm using TestNG too, I know that makes a difference in what's allowable and what's not.
Thank you!
You can use wait with try/catch to get all buttons and click on each if exist.
1.If alerts all appear at once use code below:
try{
new WebDriverWait(driver, 5)
.ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.cssSelector("button[title*='Dismiss notification']"))))
.forEach(WebElement::click);
} catch (Exception ignored){ }
2.If alerts appear singly use code below:
try{
while(true) {
new WebDriverWait(driver, 5)
.ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("button[title*='Dismiss notification']"))))
.click();
}
} catch (Exception ignored){ }
Use findElements which will return a list of 0 if the element does not exist.
E.G:
List<WebElement> x = driver.findElements(By.xpath("//button[contains(#title,'Dismiss notification')]"));
if (x.size() > 0)
{
x.get(0).click();
}
// else element is not found.
findElements will return the list no need of creating one again. Also x.size() won't work because list object has no attribute size so we have to check the length. No need of using x.get(0).click();.
driver.click(By.xpath("//button[contains(#title,'Dismiss notification')]")) should work.
x = driver.findElements(By.xpath("//button[contains(#title,'Dismiss notification')]"));
if (len(x) > 0) {
x.click();
}

Selenium Java handle object(alert dialog) exception without delaying. (unpredictable Java pop-up)

Goal: alert pop up. whether it's shown or not, I want it to continue. if it shows, have to select the checkbox, and hit continue. if not, ignore.
Blocker: if alert shows, it will handle the action and dialog will be closed. but when it's not, selenium hangs there without handling condition when it's not shown.
background: I use UFT before, maybe my logic could be wrong.
the pop up is application alert(not systems), so assumed "switch to(),accept()/dismiss() won't work. and I will add handle alert right after login and within the login method below.
Selenium framework background. : we use selenium maven framework, serenity BDD. object is set at the beginning of the page. and serenity.properties handle the time out default and so on.
Pop up objects (if it appears):
#FindBy(xpath = "//input[#id='notification-ack']")
private WebElement PcoNoticeChbx; //this is a check box, needs to be checked
#FindBy(xpath = "//button[contains(.,'Continue')]")
private WebElement PcoNoticeContinueBtn;//button to close the alert
*Log in method *
public void loginIntoExtApplication(String baseURL, String loginURL, String uId, String pwd, String extAppEnv)throws Exception {
gotoExtLoginPage(baseURL, loginURL);
enterLoginCredential(uId, pwd);
openAt("https://" + extAppEnv + ".programportaltest.hrsa.gov/sdms-
extranet/index.xhtml");
My Approaches:
//1.
if (PcoNoticeChbx!=null) {
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
} else {
System.out.println("Dialog didn't display, no need any action");
}
//2. hanged here after login actions.
if(!getDriver().findElements(By.xpath("//*[#id='submit']")).isEmpty()){
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
}
else {
System.out.println("Dialog didn't display, no need any action");
}
//3. added to watch doesn't work, it shows pending, below code failed too. I ran my Maven in Junit in debug mode. it used to work fine. but watch elements always show (pending)..
boolean isPresent = getDriver().findElements(By.id("noticebox")).size() >0
System.out.println("the diaolog exist= " + isPresent);
//4. even tried the try-catch method.
try{
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
}catch (Exception e){
// Printing logs for my report
Log.error("Report Category button element is not found.");
// After doing my work, now i want to stop my test case
throw(e);
}
return;
}
//5. tried list webelemets:
List temp = webdriver.findElements(org.openqa.selenium.By.id("noticebox"));
if (temp.Count > 0 && temp[0].Displayed) {
// script to execute if element is found
} else {
// continue the test
}
//6. and below
if (!WebDriver.findElements(By.xpath("//*[#id='submit']")).isEmpty()==true);
{
        //handle the dialog
    }
else{
//continue
}
// 7.tried with a boolean value, but it also hangs on here first steps
boolean Nbox = PcoNoticeChbx.isDisplayed(); {
if (Nbox==false)
{
System.out.println("Dialog didn't display, no need any action");
}
else if (Nbox==true) {
PcoNoticeChbx.click() ;
PcoNoticeContinueBtn.click();
}
If this is like the popups that I've dealt with they work like this:
Customer comes to site and the site checks for the existence of a cookie. If that cookie exists, the popup is never launched (ideal state). If that cookie does NOT exist (typical state), after a specified period of time a popup appears.
Customer dismisses the popup and a cookie is created with an expiration time
Once that expiration time passes, the cookie expires and the popup will fire again
You need to do some investigation and find the cookie that is created once the popup is dismissed. Clear your cache, browse to the site, and note all the cookies that exist. Wait for the popup and dismiss it. Now find the cookie that was just created and examine it. This is the cookie you need to create. There are a lot of tutorials on creating cookies. It's pretty straightforward.
Once you learn how to create the cookie, you add it to your script as described below:
Navigate to some page on the domain that you know doesn't exist, e.g. www.domain.com/some404page. We do this because it won't trigger the popup countdown and we need to be on the domain to create the cookie.
Create the cookie
Do your normal test
No more popups.
Solution found for my case.
this maybe very easy. but takes some times for me to research. hopefully it will help you.
after use of many methods, for this javascripts confirmation alert. i have used below method. all of help of .CurrentlyVisible() method. because this one, and i guess only this one will give you result even when the element does not exist or null..
if (element(NoticeContinueBtn).**isCurrentlyVisible**()==true) {
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
//else just continue
}

selenium webdriver handle windows pop [duplicate]

This question already has answers here:
Alert handling in Selenium WebDriver (selenium 2) with Java
(5 answers)
Closed 6 years ago.
I am saving image from to my local system with selenium-webdriver (using Robot class):-
First time it save perfectly.
When I run my script second time again then it tries to save same image with the same name but windows pop appear The image with this name already exists. Do wish to save again with Ok and Cancel button. How to handle this Ok button.
You can handle Windows pop-up using a 3rd party tool Auto-IT integrated with eclipse. This will consist of an script editor (where you have to write a piece of code and save as ".au3") and inspector (used to inspect the properties of the window pup-up buttons).
Refer to - https://www.autoitscript.com/site/autoit/
you could also try to just send an enter press which would press whichever button is marked by default
if its more of an overlay then a real popup (like jquery or jsf in java) then you can select the buttons using xpath
Using selenium you can accept an Alert, try the following, I know this works in C#
IAlert alert = null;
try
{
alert = BrowserProcess.SwitchTo().Alert();
}
catch (Exception e)
{
//no alerts present, everything is ok
}
if (alert != null)
{
alert.Accept();
}
In java it would be something like this:
Alert alert = driver.switchTo().alert();
alertText = alert.getText();
alert.accept();

ShowOptionDialog cancel option doesn't work

I am trying to create a GUI for my program. This particular GUI uses a JOptionsPane with a showOptionDialog. I have added a panel to that OptionsPane that has some action listeners as well as two lists and some other things, that really doesn't matter for this question though.
Quite simply I want my showOptionDialog to perform some action when the user clicks the "cancel" button. (It will basically end the program but it must be done in a certain way). Right now when the user clicks "cancel" the program continues as if the user just ended that dialog but no action is taken. I am trying to change a variable if they click cancel which will prevent the rest of the program from running. I tested with a System.out.println to see if my value was really being changed and I found that the step wasn't occurring at all. So I would like to know based upon this code what I am doing wrong. What do I need to do to make the code run correctly when the user clicks cancel?
I do not have more code to show as my program is very large and it is impossible for me to isolate this situation.
Thanks in advance for the help!
public static void displayGUI(){
int result = JOptionPane.showOptionDialog(null, getPanel(),"JOptionPane Example : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Confirm","Create Return"}, "default");
if(result == JOptionPane.CANCEL_OPTION){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
}
*This part of the code isn't being executed, even if the user selects cancel:
if(result == JOptionPane.CANCEL_OPTION){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
From your Question:
*This part of the code isn't being executed, even if the user selects cancel:
Try The integer value that is returned from the JOptionPane.showOptionDialog(). 0 Is returned if OK is selected and 1 is returned if Cancel is selected.
Modify your code as follows:
if(result == 1){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
Let me Know, If this doesn't Helps you!!!
You are telling JOptionPane to create two buttons ("Confirm" and "Create Return"), and then telling it the default button is "default" but you don't have a button with text "default". You also don't have a Cancel". The return value will be 0 if the uses picks "Confirm", or 1 if the user picks "Create Return", or CLOSED_OPTION if the user just closes the dialog.
If you take a look at the JavaDocs for JOptionPane.showOptionDialog, it tells you
Returns: an integer indicating the option chosen by the user, or
CLOSED_OPTION if the user closed the dialog
This is the index of the options array you passed to the method. In this case new String[]{"Confirm","Create Return"}
So a return value of 0 will mean Confirm was selected and 1 will mean Create Return was selected (or JOptionPane.CLOSE_OPTION if the user closed the window)
When assigning result a value you are using JOptionPane.OK_CANCEL_OPTION but in the if condition you are checking for JOptionPane.CANCEL_OPTION

if statement not returning results

I'm sending a username and password to a website for authentication purposes, after all is said and done and I've retrieved the results from the server, I've placed the results in a variable called 'response' To this point everything is working correctly
response = sb.toString();
Toast.makeText(this,"Returned Value: "+ response,0).show();
The value seen in the above Toast is the value being returned by the php script. I've used both a valid user and an invalid user and the Toast displayed above shows the correct value (i.e. "Good Login" or "Login Failed") returned by the server. I want to test for those results so I can start the appropriate activity so I've put in some test "if" statements
if("Good Login".equals(response)){
Toast.makeText(this, "Registered User" + mUsername, 0).show();
}
if("Login Failed".equals(response)){
Toast.makeText(this, "Sorry You're Not A Registered Subscriber",0).show();
}
I'm getting nothing from either one.
I've also tried
if(response.equals("Good Login")){
Toast.makeText(this, "Registered User" + mUsername, 0).show();
}
if(response.equals("Login Failed")){
Toast.makeText(this, "Sorry You're Not A Registered Subscriber",0).show();
}
With the same results. Not sure what else to test for. Is there a better way to test for success or failure?
Thanks
Debug (or print) the exact value of the response variable.
It is likely that there are whitespaces, so you may need to have response = response.trim()
I would return an integer error code rather than some string to check the error response.
Make sure you are returning the correct case, otherwise use equalsIgnoreCase
The Java string equals function is fully case/spacing sensitive compare.
So if:response = "Good Login " or if it contains extra-spaces or non-printing characters then it will fail the test.
It would be a good idea to strip all whitespace, even the internal ones. Here's a SO question about doing just that. Also use String.equalsCaseInsesitive() when doing that actual comparison.

Categories