There are two types of alerts,
#1.) Browser alert: This alert you can simply handle using swithTo().alert() function as given below.
You can call this function everytime after your switch/any action.
public void dismissAlert(){
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}
}
Above function ignores exception. So, even if you face any exception, your program will not stop.
#2) Windows Alert: Windows alert are produced by calling windows library and can not be handeled using JavaScript. So, such functions can not be handeled using Selenium. You may have to use3rd party tools like AutoIT to handle such alerts.
Eg. Assume that you have file download dialog box popping in, you can use sample AutoIT script as below and create runnable exe file.
WinWait("[TITLE:Opening ; CLASS:MozillaDialogClass]","", 10) //Explanation â âIt will wait for the title â opening , type- mozilladialogclass, for 10 secs
If WinExists("[TITLE:Opening ; CLASS:MozillaDialogClass]") Then // if condition
WinActivate("[TITLE:Opening ; CLASS:MozillaDialogClass]") // if that title is found it will activate and perform below actions
Send("{DOWN}") // perform down arrow operation
Sleep(10) // wait for 10 secs
Send("{TAB}") // perform tab operation
Sleep(10) // wait for 10 secs
Send("{TAB}") // perform tab operation
Sleep(10) // wait for 10 secs
Send("{ENTER}") // press enter button
EndIf // end of if condition
Once you have runnable file ready, you can execute it after every action of yours.
You can execute your exe file using runtime as given sample below.
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("submit")).click();
// below line execute the AutoIT script .
Runtime.getRuntime().exec("FileUpload.exe");
driver.findElement(By.id("search")).sendKeys("AutoIT in Selenium");
driver.findElement(By.id("submit_form")).click();
Hope that answers your question!