How to wait for an alert in Selenium webdriver ? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
selenium 2.4.0, how to check for presence of an alert
I am using the following code to close the alert window :
Alert alert3 = driver.switchTo().alert();
alert3.dismiss();
The alert appears a few seconds after the opening of the main window.
How can I wait and check if alert appears ?

No default method for waiting for alert.
but, you can write your own method something like this.
waitForAlert(WebDriver driver)
{
int i=0;
while(i++<5)
{
try
{
Alert alert = driver.switchTo().alert();
break;
}
catch(NoAlertPresentException e)
{
Thread.sleep(1000);
continue;
}
}
}

public boolean isAlertPresent() {
boolean presentFlag = false;
try {
// Check the presence of alert
Alert alert = driver.switchTo().alert();
// Alert present; set the flag
presentFlag = true;
// if present consume the alert
alert.accept();
} catch (NoAlertPresentException ex) {
// Alert not present
ex.printStackTrace();
}
return presentFlag;
}

Related

UnhandledAlertException doesn't catch alert exception

please check on this snippet:
try {
myTransactionsPage.getEnterTransaction();
} catch (UnhandledAlertException e) {
String alertText = e.getAlertText();
assertThat(alertText.contains("Please enter text"));
}
driver.switchTo().alert().accept();
I want to make an assertion about alert text. When I press 'add transaction' key (which is simple .click()) i want to catch an unhandleAlertException. Which is so surprising i get
org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Please enter text in the Paid To/From input box.}
Have you encountered this problem? Catching an exception doesn't catch it?
I have handled alert exception,
try {
//click button
} catch (UnhandledAlertException e) {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
assertThat(alertText.contains("Please enter text"));
alert.accept();
}
The UnexpectedAlertPresentException is thrown when you do not deal with the alert box.
It is not possible to take screenshot with the alert box using selenium. Either you need to accept or decline the alert box.
In my scenario, I accept the alert box and take the screenshot of the URL.
try {
//capture the screenshot
} catch (UnexpectedAlertPresentException e) {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
}

Issue facing in Selenium handling multiple window

I have written the below script where first i will click on FACEBOOK Sign in button then the pop up for FACEBOOK login page will open in a separate window.I am entering the id and password. But my issue is when i am clicking on the login button then that window will disappear and my parent window URL will change. How to handle the changed URL. I need to perform some operation on that. I am aware that i can move to parent window,but the issue is when i click on login the URL changes
private void facebookSignIn(){
WebElement element=null;
try{
element = driver.findElement(By.xpath(".//*[#id='signin_facebook_button']/div[2]"));
String mwh=driver.getWindowHandle();
element.click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
Set<String> set=driver.getWindowHandles();
Iterator<String> iterator=set.iterator();
while(iterator.hasNext())
{
String popupHandle=iterator.next().toString();
if(!popupHandle.contains(mwh))
{
driver.switchTo().window(popupHandle);
element = driver.findElement(By.xpath(".//*[#id='email']"));
element.sendKeys(account);
element = driver.findElement(By.xpath(".//*[#id='pass']"));
element.sendKeys(password);
element = driver.findElement(By.xpath(".//*[#id='u_0_2']"));
countDownLatch.countDown();
countDownLatch.await();
element.click();
System.out.println("Click Done");
//driver.switchTo().window(mwh);
}
}
start = System.currentTimeMillis();
counter++;
if(counter==1)
{
startTime=System.currentTimeMillis();
}
#SuppressWarnings("unused")
WebElement sso_logout = (new WebDriverWait(driver,30)).until(ExpectedConditions.visibilityOfElementLocated(By.id("sso_logout")));
end = System.currentTimeMillis();
endTime=System.currentTimeMillis();
try{
element = driver.findElement(By.id("sso_logout"));
element.click();
}
catch(Exception e)
{
System.out.println("Exception from SSO_Logout");
}
double temp=(double)(end-start)/1000;
latencyMap.put(Thread.currentThread().getName(),temp) ;
System.out.println(Thread.currentThread().getName()+"-->Done");
}
catch(Exception e){
countDownLatch.countDown();
totalNumberOfUsers--;
System.out.println(account);
System.out.println(e.getMessage());
}
}
WindowHandle is not based on url, so it shouldn't effect you. If you need to switch back do something like that:
String parentHandle = driver.getWindowHandle();
// switch to the new window
for (String winHandle : driver.getWindowHandles()) {
if (!winHandle.equals(parentHandle))
{
driver.switchTo().window(winHandle);
}
}
//do something with the new window
element = driver.findElement(By.xpath(".//*[#id='email']"));
element.sendKeys(account);
element = driver.findElement(By.xpath(".//*[#id='pass']"));
element.sendKeys(password);
element = driver.findElement(By.xpath(".//*[#id='u_0_2']"));
countDownLatch.countDown();
countDownLatch.await();
element.click();
System.out.println("Click Done");
// switch back to the old window
driver.switchTo().window(parentHandle);
// if the new window is closed by its on
driver.switchTo().window(driver.getWindowHandle());
WindowHandle example:
"CDwindow-0D7BB6F6-A7E0-4DCE-B4D0-F202E85D982D"

org.openqa.selenium.UnhandledAlertException: unexpected alert open

I am using a Chrome Driver and trying to test a webpage.
Normally it runs fine, but sometimes I get exceptions:
org.openqa.selenium.UnhandledAlertException: unexpected alert open
(Session info: chrome=38.0.2125.111)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 16 milliseconds: null
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
System info: host: 'Casper-PC', ip: '10.0.0.4', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Then I tried to handle the alert:
Alert alt = driver.switchTo().alert();
alt.accept();
But this time I received:
org.openqa.selenium.NoAlertPresentException
I am attaching the screenshots of the alert:
I am not able to figure out what to do now. The problem is that I do not always receive this exception. And when it occurs, the test fails.
I had this problem too. It was due to the default behaviour of the driver when it encounters an alert. The default behaviour was set to "ACCEPT", thus the alert was closed automatically, and the switchTo().alert() couldn't find it.
The solution is to modify the default behaviour of the driver ("IGNORE"), so that it doesn't close the alert:
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
d = new FirefoxDriver(dc);
Then you can handle it:
try {
click(myButton);
} catch (UnhandledAlertException f) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert data: " + alertText);
alert.accept();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
You can use Wait functionality in Selenium WebDriver to wait for an alert, and accept it once it is available.
In C# -
public static void HandleAlert(IWebDriver driver, WebDriverWait wait)
{
if (wait == null)
{
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
}
try
{
IAlert alert = wait.Until(drv => {
try
{
return drv.SwitchTo().Alert();
}
catch (NoAlertPresentException)
{
return null;
}
});
alert.Accept();
}
catch (WebDriverTimeoutException) { /* Ignore */ }
}
Its equivalent in Java -
public static void HandleAlert(WebDriver driver, WebDriverWait wait) {
if (wait == null) {
wait = new WebDriverWait(driver, 5);
}
try {
Alert alert = wait.Until(new ExpectedCondition<Alert>{
return new ExpectedCondition<Alert>() {
#Override
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch (NoAlertPresentException e) {
return null;
}
}
}
});
alert.Accept();
} catch (WebDriverTimeoutException) { /* Ignore */ }
}
It will wait for 5 seconds until an alert is present, you can catch the exception and deal with it, if the expected alert is not available.
Is your switch to alert within a try/catch block? You may also want to add a wait timeout to see if the alert shows up after a certain delay
try {
// Add a wait timeout before this statement to make
// sure you are not checking for the alert too soon.
Alert alt = driver.switchTo().alert();
alt.accept();
} catch(NoAlertPresentException noe) {
// No alert found on page, proceed with test.
}
UnhandledAlertException
is thrown when it encounters an unhanded alert box popping out. You need to set your code to act normally unless an alert box scenario is found. This overcomes your problem.
try {
System.out.println("Opening page: {}");
driver.get({Add URL});
System.out.println("Wait a bit for the page to render");
TimeUnit.SECONDS.sleep(5);
System.out.println("Taking Screenshot");
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "C:\\images";
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
} catch (UnhandledAlertException ex) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "C:\\Users";
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
driver.close();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
After click event add this below code to handle
try{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
catch (org.openqa.selenium.UnhandledAlertException e) {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText().trim();
System.out.println("Alert data: "+ alertText);
alert.dismiss();}
... do other things
driver.close();
DesiredCapabilities firefox = DesiredCapabilities.firefox();
firefox.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
You can use UnexpectedAlertBehaviour.ACCEPT or UnexpectedAlertBehaviour.DISMISS
I was facing the same issue and I made this below changes.
try {
click(myButton);
} catch (UnhandledAlertException f) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert data: " + alertText);
alert.accept();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
It worked amazingly.
I tried this below code, it perfectly worked for me (Chrome)
try{
System.out.println("Waiting for Alert");
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.alertIsPresent()).dismiss();
System.out.println("Alert Displayed");
}
catch (Exception e){
System.out.println("Alert not Displayed");
}
You can try this snippet:
public void acceptAlertIfAvailable(long timeout)
{
long waitForAlert= System.currentTimeMillis() + timeout;
boolean boolFound = false;
do
{
try
{
Alert alert = this.driver.switchTo().alert();
if (alert != null)
{
alert.accept();
boolFound = true;
}
}
catch (NoAlertPresentException ex) {}
} while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
}
Following is working for me
private void acceptSecurityAlert() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(new Function<WebDriver, Alert>() {
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch(NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
}
The below code will help to handle unexpected alerts in selenium
try{
} catch (Exception e) {
if(e.toString().contains("org.openqa.selenium.UnhandledAlertException"))
{
Alert alert = getDriver().switchTo().alert();
alert.accept();
}
}

How to reset the name of user in the field?

There is a table list of username, from these table I have edited the username "Pra" to "Pra1", but now when I come to the user table list its not finding a user with the name "Pra" because its updated with "Pra1".
So, what I want is after updating an username in the search filter it search with updated username (With "Pra1").
Below are the running code upto the updated username please help me after that:
public class InsSystemCenter {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("URL");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Verify the insfocus system center page has been opened or not by
// xpath//
if (driver.findElement(By.xpath("/html/body/table/tbody/tr[1]/td/h1")) != null) {
System.out.println("Center has been opened");
} else {
System.out.println("Center is not displaying");
}
WebElement userName = driver.findElement(By.name("username"));
userName.sendKeys("pra");
WebElement password = driver.findElement(By.name("password"));
password.sendKeys("123456");
WebElement signIn = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[2]/td/table/tbody/tr[1]/td/form/center/div/table/tbody/tr[4]/td/input"));
signIn.click();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Verify that welcome page is displayed or not//
WebElement welcomePageVerify = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div[2]/span"));
if (welcomePageVerify.isDisplayed()) {
System.out.println("Welcome page is displaying");
} else {
System.out.println("Welcome page is not displaying");
}
// Try to click on the tab name "Settings" by xpath//
WebElement settings = driver.findElement(By
.xpath("/html/body/table/tbody/tr[2]/td/ul/li[3]/a"));
settings.click();
// Verifying that after clicking on "Setting" it opens a database page
// or not//
WebElement settingsVerify = driver
.findElement(By
.xpath("/html/body/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]/h1/span"));
if (settingsVerify.isDisplayed()) {
System.out
.println("Database page is displayed after clicking on Setting tab");
} else {
System.out.println("Database page is not displaying");
}
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Click on the button "Users" by xpath, so that it goes to the page
// where it show the list of users //
WebElement users = driver
.findElement(By
.xpath("/html/body/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[1]/p/a[2]"));
users.click();
// Verifying for users page opened or not//
WebElement usersPageVerify = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]/h1"));
if (usersPageVerify.isDisplayed()) {
System.out
.println("Users page is displayed after clicking on users button");
} else {
System.out.println("Users page is not displaying");
}
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
System.out.println("Total time take " + new Date());
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
System.out.println("Total time take " + new Date());
WebElement usUserName = driver.findElement(By.id("g_UserName"));
usUserName.sendKeys("Pra");
usUserName.sendKeys(Keys.ENTER);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
usUserName.sendKeys(Keys.TAB);
System.out.println("Total time take " + new Date());
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
// Checked the checkbox of find elemet or user//
WebElement checkbox = driver.findElement(By.id("jqg_tblMainTable_243"));
checkbox.click();
// After checked the checkbox it enables the edit button for edit the
// user//
WebElement editButton = driver.findElement(By.id("btnEdit"));
editButton.click();
// ------------Edit user popup--------------//
// Verify edit popup opened or not//
String source = driver.getPageSource();
int a = source.indexOf("Edit User:");
if (a > 0) {
System.out.println("Edit user popup is displayed");
} else {
System.out.println("Edit user popup is not displaying");
}
// All the WebElement parameter is located here//
WebElement euUserName = driver.findElement(By.id("UserName"));
euUserName.clear();
euUserName.sendKeys("pra1");
WebElement euFullName = driver.findElement(By.id("txtFullName"));
euFullName.clear();
euFullName.sendKeys("pra1");
WebElement euPassword = driver.findElement(By.id("txtPassword"));
euPassword.sendKeys("123456");
WebElement euConfirmPassword = driver.findElement(By
.id("txtConfirmPassword"));
euConfirmPassword.sendKeys("123456");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
WebElement dropdown = driver.findElement(By.id("RoleID"));
// Verify dropdown is displayed or not not //
if (dropdown.findElement(By.id("RoleID")) != null) {
System.out.println("Dropdown is displayed");
} else {
System.out.println("Dropdown is not displaying");
}
Select clickThis = new Select(dropdown);
clickThis.selectByVisibleText("Normal");
System.out.println("Drop down values "+clickThis.getOptions().get(0).getText());
WebElement euUserDetail = driver.findElement(By.id("UserDetails"));
euUserDetail.clear();
euUserDetail.sendKeys("pra1");
WebElement euOk= driver.findElement(By.xpath("/html/body/div[3]/div[3]/div/button[1]"));
euOk.click();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
driver.quit();
}
}
Just call clear() method before your calling sendKeys("your text").
This should work.
Just use the clear function before passing the value to the webelement
WebElement userName = driver.findElement(By.name("username"));
userName.clear();
userName.sendKeys("pra");
Same way you can use for all the elements.
ok i can't even be bothered trying to read a 7 million line long main method
1) refactor it in to separate logical methods (responsibility driven design)
2) when you have done that post us the code responsible for your issues
3) maybe look at assigning the value you want to search on to a temporary variable so you can find it again?

How to use close alert and get text

Every Java code export from selenium ide will have this method..But it is the same with method for iselementpresent because I cant figured out how to use it:
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
What need to be put exactly in the try code?
The above method is not same as isElementPresent(). The closeAlertAndGetItsText() method is for handling alert boxes in your web application.
Where ever you need to handle the alert boxes in your web application, you can simply make a call to this closeAlertAndGetItsText() method. closeAlertAndGetItsText() method will click OK on the alert box and alert.getText() will provide you the text that was present in the alert box.
isElementPresent() is a method, which you will call when you need to find whether a particular element is present in the webpage or not. There are many implementations of isElementPresent() Find below some of them.
private boolean isElementPresent(WebDriver driver, String id) {
try {
driver.getWrappedDriver().findElement(By.id(id));
return true;
} catch (Exception e) {
return false;
}
}
private boolean isElementPresent(WebDriver driver, String classname) {
try {
driver.findElements(By.className("someclass")).size() > 0;
return true;
} catch (Exception e) {
return false;
}
}

Categories

Resources