One alerts popup is appearing after saving data. How to check popup visibility using Selenium with java
I would suggest you to use ExpectedConditions like below to check whether the alert is present or not like below:
WebDriverWait wait = new WebDriverWait(driver, 30);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
{
System.out.println("No alert");
else{
System.out.println("Alert present");
}
}
To accept that alert you can use:
driver.switchTo().alert().accept();
To close that alert you can use:
driver.switchTo().alert().dismiss();
To send some values to the alert box you can use:
driver.switchTo().alert().sendKeys("Text");
We can also use try-catch block like below:
public boolean alertPresent()
{
try
{
driver.switchTo().alert();
return true;
}
catch (NoAlertPresentException Ex)
{
return false;
}
}
driver.switchTo().alert();
This will help you to switch to the alert popup window and you can check for the visiblility.
Ok, Find the xpath or id of the popup let's take one example
WebElement popUp = driver.findElement(By.xpath("xpath of the popup"));
if (popUp.isDisplayed())
{
WebElement btnOk = driver.findElement(By.xpath("xpath of the button in alert"));
btnOk.click();
System.out.println("Pop up displayed and button clicked");
}
else
{
System.out.println("Pop up Not found");
}
their is second way you can handle alerts and check if that presents
try
{
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()+" Alert is Displayed");
}
catch(NoAlertPresentException ex)
{
System.out.println("Alert is NOT Displayed");
}
Related
I have one button which sometimes does not do the actual click, due to that i wrote a code to handle it with a while loop where it will click until it finds out a new assignment title of the page. But this is not working as expected. Please help me, thanks in advance.
String titleWhenLoad = driver.findElement(By.xpath("//span[#class='assignment_title']")).getText();
String titleNext = titleWhenLoad;
while ((titleWhenLoad.equals(titleNext))
&& (driver.findElement(By.xpath("//span[#class='assignment_title']")).isDisplayed())) {
WebElement btn = driver.findElement(By.xpath("//button[contains(text(),'Submit')]"))
btn.click();
if (driver.findElement(By.xpath("//span[#class='assignment_title']")).isDisplayed()) {
titleNext = driver.findElement(By.xpath("//span[#class='assignment_title']")).getText();
} else {
break;
}
}
You can use WebDriverWait utilizing .invisibilityOfElementWithText to wait a element with specific text disappear.
To click the button target, I suggest to use Actions class.
Check it out:
String titleWhenLoad = driver.findElement(By.xpath("//span[#class='assignment_title']")).getText();
boolean findNewTitle = false;
while (!findNewTitle) {
try {
new WebDriverWait(driver, 3).until(ExpectedConditions.invisibilityOfElementWithText(By.xpath("//span[#class='assignment_title']"), titleWhenLoad));
findNewTitle = true;
} catch (Exception e) {
WebElement btn = driver.findElement(By.xpath("//button[contains(text(),'Submit')]"));
Actions builder = new Actions(driver);
builder.moveToElement(btn).click(btn).build().perform();
}
}
Import the following:
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.interactions.Actions;
Reference:
https://www.selenium.dev/documentation/en/webdriver/waits/#expected-conditions
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html
For my CS class they require us to use JavaFX alerts. I can make an alert appear, but how do I get what button was clicked? What would be the best way to go about getting this data?
Also if possible, I'd like to make it have a drop down panel and when the user selects and option the alert closes and prints what the user selected.
Here's some example code that I have. When I click one of the buttons, it just closes the dialog.
Alert a = new Alert(AlertType.NONE, "Promote pawn to:", new ButtonType("Queen"), new ButtonType("Rook"));
a.setTitle("Title");
a.setHeaderText("My header text");
a.setResizable(true);
a.setContentText("Content text");
a.showAndWait();
Thanks,
You can do
ButtonType queen = new ButtonType("Queen");
ButtonType rook = new ButtonType("Rook");
Alert a = new Alert(AlertType.NONE, "Promote pawn to:", queen, rook);
a.setTitle("Title");
a.setHeaderText("My header text");
a.setResizable(true);
a.setContentText("Content text");
a.showAndWait().ifPresent(response -> {
if (response == queen) {
// promote to queen...
} else if (response == rook) {
// promote to rook...
}
});
İf you want to do it with Non-Blocking type of code:
final Alert alert2 = new Alert(Alert.AlertType.CONFIRMATION);
alert2.show();
alert2.setOnCloseRequest(new EventHandler<DialogEvent>() {
#Override
public void handle(DialogEvent event) {
ButtonType result=alert2.getResult();
String resultText=result.getText();
//result logic
}
});
Correct wait to wait for an element to disappear?
I have an ajax loader which loads after for example clicking on a button, is my method correct inorder to wait for a particular load bar which takes the full width and height of a screen to disappear?
public void waitUntilAjaxLoaderDisapears() {
// Wait up to 2minutes for the element to disappear
WebDriverWait ajaxWait = new WebDriverWait(this.driver, 60);
ajaxWait.pollingEvery(100, TimeUnit.SECONDS);
try {
//tempWait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal-body")));
ajaxWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[contains(#class, 'ajax_loader')]")));
} catch (UnhandledAlertException e) {
Alert alert = driver.switchTo().alert();
alert.accept();
}catch (NoAlertPresentException e) {
//
}catch (StaleElementReferenceException e) {
// do nothing
} catch (NullPointerException e) {
// do nothing
} catch (Exception e) {
// do nothing
}
}
I think i got the issue. The polling time should be less than the overall wait time. So it can be,
WebDriverWait ajaxWait = new WebDriverWait(this.driver, 60);
ajaxWait.pollingEvery(**5**, TimeUnit.SECONDS);
Instead of
WebDriverWait ajaxWait = new WebDriverWait(this.driver, 60);
ajaxWait.pollingEvery(100, TimeUnit.SECONDS);
Hope this helps you. Thanks.
public void testSuccess() throws InterruptedException {
System.out.println("test arribute popup");
Thread.sleep(3000);
WebElement searchBtn = driver.findElement(By.xpath(".//*[#id='investedList']/span/span[2]/span"));
Actions action = new Actions(driver);
action.moveToElement(searchBtn).perform();
Thread.sleep(3000);
}
when mouse move into button there is popup text display as "invested list"
how to test this using selenium
try this code:
List<WebElement> overlaysTooltips = driver.findElements(By.xpath(".//*[#id='investedList']/span/span[2]/span"));
for(int i = 0; i < overlaysTooltips.size(); i++){
Actions builder = new Actions(driver);
builder.moveToElement(overlaysTooltips.get(i)).perform();
//get button text after hover
if((overlaysTooltips.get(i).getAttribute("value").equals("//ur button hover string")){
//ur condition
Thread.sleep(3000);
}
}
you can use other button attribute what is in ur html code as i dont know what kind of attribute in ur html code there.
like this:
overlaysTooltips.get(i).getAttribute("id")
or
overlaysTooltips.get(i).getAttribute("class")
or
overlaysTooltips.get(i).getAttribute("name")
I would like to disable the close x in the upper left corner of my JOptionPane how would I do this?
Michael,
I don't know how to disable the Close[x] button. Alternatively, you can do nothing when user clicks on it. Check the code below:
JOptionPane pane = new JOptionPane("message");
JDialog dialog = pane.createDialog(null, "Title");
dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setVisible(true);
Is it reasonable for you?
you can overwrite your exit button by a cancel button declared in JOptionPane and handle your cancellation operation accordingly:
JOptionPane optionPane= new JOptionPane("message", JOptionPane.OK_CANCEL_OPTION);
final JDialog dialog = optionPane.createDialog(null, "Input");
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
#Override public void windowClosing(WindowEvent e) {
optionPane.setValue(JOptionPane.CANCEL_OPTION);
}
});
if (JOptionPane.CANCEL_OPTION!= ((Integer) optionPane.getValue()).intValue())
throw new myCancellationException();
You could always just show the dialog again when the user tries to close it without selecting an option. There's an example of how to override the default closing behavior at sun.com. Look under "Stopping Automatic Dialog Closing" and they have the following code:
final JOptionPane optionPane = new JOptionPane(
"The only way to close this dialog is by\n"
+ "pressing one of the following buttons.\n"
+ "Do you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
final JDialog dialog = new JDialog(frame,
"Click a button",
true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setLabel("Thwarted user attempt to close window.");
}
});
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (dialog.isVisible()
&& (e.getSource() == optionPane)
&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
//If you were going to check something
//before closing the window, you'd do
//it here.
dialog.setVisible(false);
}
}
});
dialog.pack();
dialog.setVisible(true);
int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
setLabel("Try using the window decorations "
+ "to close the non-auto-closing dialog. "
+ "You can't!");
}
Using that code, you could easily adapt the commented section to only allow the window to be closed when the user has clicked one of the available options and not the close button.
I'm not sure if there is a way to do this in JOptionPane.
Usually when people want more flexibility than JOptionPane offers (it's basically a bunch of static factories for a few dialogs), they write their own dialogs using JDialog.
JDialog offers the inherited method setUndecorated, which eliminates the X altogether. It's more work but you can make your dialog look however you want.