If you attempt to interact with something on the website you will get an UnhandledAlertException. This is similar to trying to click on the website when a modal dialog is present. The clicks on the website will fail because the modal dialog is in the way.
You need to figure out how to handle this. One way would we to wrap all calls in a try-catch. You would have to do something like:
boolean click_not_done = true;
while(click_not_done) {
try {
// find an element
// click the element
click_not_done = false;
} catch(UnhandledAlertException uae) {
// switch to the alert and handle it
}
}
Now this is pretty ugly and cumbersome. So although this would work, it would be difficult to maintain. Being too difficult to maintain is the number one killer to test automation. So this isn't really a good solution.
If you know when a dialog will appear, handling the alert right away would be a good idea. For example, if I had the code:
// find an element
// click the element
// alert appears because of the previous action
// switch to the alert
// handle the alert
// continue with the rest of your program
This works great but only if you know when the alert dialog will appear. The alert dialog must occur 100% of the time if you use this solution. What if you are testing a website where the dialog might appear 30% of the time? Then you can use an if statement like you have below. Your code would become:
// find an element
// click the element
// if an alert appears because of the previous action {
// handle the alert
// }
// continue with the rest of your program
You don't need to watch for the dialog on every action. You only need to do it once or twice in a test.
The really hard case is when a dialog will randomly appear (e.g. asking user if they want to participate in a survey). In these cases you can set a capability for your WebDriver instance on how to handle the unexpected alert. For example, if I create my WebDriver instance using:
WebDriver driver = new ChromeDriver();
what I can do instance is:
import org.openqa.selenium.UnexpectedAlertBehaviour;
import static org.openqa.selenium.remote.CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR;
DesiredCapabilities dc = DesiredCapabilities.chrome();
dc.setCapability(UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.DISMISS);
WebDriver driver = new ChromeDriver(dc);
By creating my WebDriver instance this way, whenever an unexpected alert appears, it will automatically cancel the dialog. You could also set the default behaviour to always ACCEPT the dialog. You do have to set the default behaviour to the same all the time.
Darrell