Prabhakar Y
Prabhakar Y

Reputation: 87

How to handle Javascript Alert/pop up window in selenium webdriver

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?

Upvotes: 3

Views: 43967

Answers (5)

YaDav MaNish
YaDav MaNish

Reputation: 1352

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

Upvotes: 0

Java By Kiran
Java By Kiran

Reputation: 93

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

}

Upvotes: 0

Subh
Subh

Reputation: 4424

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

Upvotes: 11

Zach
Zach

Reputation: 1006

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

Upvotes: 7

Margus
Margus

Reputation: 20038

Mock it out. Call javascript behind the UI directly:

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

Upvotes: 2

Related Questions