3

I am not sure whether selenium webdriver can handle Javascript alert/pop-up window.

I have a scenario like
1. User uploads a xls file and click on upload button
2. Alert/Pop-up window will be displayed . Click "OK" on window

Am able to automate the above scenario but the Alert/pop-up window is displayed while running the scripts.

Is their anyway workaround that we can handle javascript alert/pop-up window?

5 Answers 5

11

You can also try waiting for the alert to appear and then accepting it.

Below is the code for that (after the upload button is clicked):

try{
   //Wait 10 seconds till alert is present
   WebDriverWait wait = new WebDriverWait(driver, 10);
   Alert alert = wait.until(ExpectedConditions.alertIsPresent());

   //Accepting alert.
   alert.accept();
   System.out.println("Accepted the alert successfully.");
}catch(Throwable e){
   System.err.println("Error came while waiting for the alert popup. "+e.getMessage());
}
Sign up to request clarification or add additional context in comments.

Comments

7

Switch to default content Dismiss alert after accepting "OK" Otherwise your alert is from a different window which you'll have to switch to in order to dismiss

driver.switchTo().alert().accept();    
driver.switchTo().alert().dismiss();  
driver.switchTo().alert().defaultConent();  

Comments

2

Mock it out. Call javascript behind the UI directly:

WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
    ((JavascriptExecutor)driver).executeScript("yourScript();");
}

Comments

0

There are the four methods that we would be using along with the Alert interface:

void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.

void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.

String getText() – The getText() method returns the text displayed on the alert box.

void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.

if(isAlertPresent(ldriver)){
Alert alert = ldriver.switchTo().alert(); 
System.out.println(alert.getText());
alert.accept();

}

Comments

0

Alert is a interface which have the abstract methods below

void accept();
void dismiss();
String getText();
void sendKeys(String keysToSend);

new WebDriverWait(driver,10).
until(ExpectedConditions.alertIsPresent()).accept();

alertIsPresent() internally return the 
driver.switchTo.alert(); then we don't have to write it explicitly

hope this is been helpful

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.