When running my testscripts, sometimes an UnhandledAlertException appears. The problem is that the Alert is totally random and I have no way of knowing when it's going to appear.
I need to know what the alert says, so this can be fixed. But selenium dismis the alert the moment it appears.
Can someone tell me how to handle such an alert, so that i can see what the alert says?
You can catch the exception and then handle the alert, by either accepting, dismissing, or getting the text of the alert.
For a C# example:
try
{
// Code that is sometimes throwing the exception.
}
catch (UnhandledAlertException)
{
IAlert alert = webDriver.SwitchTo().Alert();
Console.WriteLine(alert.Text);
}
Also, you didn't specify which browser you're using, but if it is Internet Explorer, then look at the InternetExplorerOptions class, which provides an option for specifying the default way you want to handle alerts.
Related
I have a test that has been running fine for months. One thing it does is cause an alert and then verify the alert text. This is running with Selenium, Java and Chrome Driver 76.0.3809.68.
Lately it has been giving me the error:
"No such alert".
What happens is it clicks a button and waits for an alert if there:
try {
button.click();
} catch (UnhandledAlertException ex) {
// nothing
}
// then here goes code to accept the alert and get the text
when stepping through I see the alert. When I run it, I see the alert but it disappears. I did read something in the (Chrome Driver) release notes about unexpected alerts but it was a bit vague.
We have a global page which sets the options for Chrome, but everyone uses it and I don't want to screw up for other people. I did do it locally (did not git push) and it worked when I set the options before creating the driver.
Then I tried to do this, which does not seem to work. Should it, or once the web page is retrieved, can you not change options?
// Somewhere after web page retrieved this gets called:
public void setIgnoreAlert() {
ChromeDriver cd = (ChromeDriver) driver;
ChromeOptions cap = new ChromeOptions();
cap.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
Capabilities other = cap;
cd.getCapabilities().merge(other);
}
Which I was really hoping would work, but did not. Do you have to set the behavior before the Chrome instance comes up? That is, can you not set it as I did above? Any other suggestions on how to set it after the Chrome instance is up?
--- added later to answer question
This is done immediately after the try-catch block with button.click():
The method configPage.getAndHandleAlertPopUp() does the following:
public String getAndHandleAlertPopUp() {
Alert alert = driver.switchTo().alert();
String alertPopup = alert.getText();
alert.accept();
return alertPopup;
}
You saw it right. As per the User Prompts section within WebDriver - W3C Recommendation:
The common denominator for user prompts is that they are modal windows requiring users to interact with them before the event loop is unpaused and control is returned to the current top-level browsing context.
By default user prompts are not handled automatically unless a user prompt handler has been defined. When a user prompt appears, it is the task of the subsequent command to handle it. If the subsequent requested command is not one listed in this chapter, an unexpected alert open error will be returned.
User prompts that are spawned from beforeunload event handlers, are dismissed implicitly upon navigation or close window, regardless of the defined user prompt handler.
A user prompt has an associated user prompt message that is the string message shown to the user, or null if the message length is 0.
As per the discussion in ChromeDriver should return user prompt (or alert) text in unhandled alert error response:
When a user prompt handler is triggered, the W3C Specification states that the error response should return an "annotated unexpected alert open error" which includes an optional dictionary containing the text of the user prompt. ChromeDriver should supply the optional information.
Clearly, ChromeDriver was not compliant with this standard as the #Test were annotated with #NotYetImplemented as follows:
#Test
#NotYetImplemented(CHROME)
#NotYetImplemented(CHROMIUMEDGE)
#Ignore(value = HTMLUNIT, reason = "https://github.com/SeleniumHQ/htmlunit-driver/issues/57")
#NotYetImplemented(value = MARIONETTE,
reason = "https://bugzilla.mozilla.org/show_bug.cgi?id=1279211")
#NotYetImplemented(EDGE)
public void testIncludesAlertTextInUnhandledAlertException() {
driver.get(alertPage("cheese"));
driver.findElement(By.id("alert")).click();
wait.until(alertIsPresent());
assertThatExceptionOfType(UnhandledAlertException.class)
.isThrownBy(driver::getTitle)
.withMessageContaining("cheese")
.satisfies(ex -> assertThat(ex.getAlertText()).isEqualTo("cheese"));
}
Now this feature have been implemented with ChromeDriver v76.0:
Resolved issue 2869: ChromeDriver should return user prompt (or alert) text in unhandled alert error response [Pri-2]
So you have to handle the alert as a mandatory measure.
A bit more of your code code block for ...then here goes code to accept the alert and get the text... would have helped us to debug the issue in a better way. However here are the options:
Induce WebDriverWait for alertIsPresent() as follows:
new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
Your code trials was perfect perhaps as you have passed the CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE in a structured way:
public void setIgnoreAlert() {
ChromeOptions opt = new ChromeOptions();
opt.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
}
Another perspective would be to disable the beforeunload event handlers and you can find a couple of related discussions in:
How to disable a “Reload site? Changes you made may not be saved” popup for (python) selenium tests in chrome?
How to handle below Internet Explorer popup “Are you sure you want to leave this page?” through Selenium
Note: Once the WebDriver and Web Browser instances are initialized you won't be able to change the configuration on the run. Even if you are able to extract the Session ID, Cookies and other capabilities and session attributes from the Browsing Session still you won't be able to alter those attributes of the WebDriver.
You can find a detailed discussion in How can I reconnect to the browser opened by webdriver with selenium?
I know how to handle alerts but when they come unexpectedly then I am not able to handle them and my script failed. When these alert comes, there is no exception and script keeps on running in background without performing any action. I want handle any unexpected alert thrown by application when my script is running.
I will be very thankful if you share your ways to handle an unexpected alert.
you can use
DesiredCapabilities capablity = DesiredCapabilities.internetExplorer();
capablity .setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
driver = new InternetExplorerDriver(capablity);
OS: Windows 10 Enterprise
Selenium Version: 3.3.1
Browser: Internet Explorer 11
Browser Version: 11.953.14393.0
I was running the same test script for last 3 months. Suddenly last week it started failing in verifying the alert text. One difference I could find is now if the same alert is displayed within a short time span there is a warning with checkbox. Warning message is don't let this page create more messages.
Alert alert = driver.switchTo().alert();
alertText = alert.getText();
alert.getText() should return the text.
Is there any way to disable this warning message in IE11 ? If not how can I handle this in Selenium Webdriver.?
Here is the link to handle alerts in Selenium.
Link to help
To point you specific piece of code, take a look at Lines 41 to 53 in code of article.
Hope this helps.
The problem you have now is that alert is coming for very less time, which you can handle by checking whether the alert is present or not.
Try this code it might help.
WebDriverWait wait = new WebDriverWait(driver, 10);
try {
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
} catch (Exception e) {
throw e;
}
Let me know if it works.
My company wants me to develop a "Visual" GUI style BDD function using JBehave and Selenium, which uses javascript alert/confirm popup window to prompt user what is the exact step the running test reaches, eg:
Given I goto "www.google.com"
When I login
So we want to add Javascript alert window to popup during the automation test, the popped up window has the "OK" button, so when user click the OK button, the test will continue to the next step, and so on...
My issue is: I wrote a javascript func using Selenium's executeScript API which invoke the pop up alert window:
public void stepText(String step) {
executeScript("alert('"+step+"');");
}
So I expect when I click the OK button, the popped up window will disappear and test will continue to next step... But what shocked me is that when I click it, the test throw exception and crashed...
The exception is: selenium.WebDriverException
But I found if I add the following code to make the test automatically detect the alert window and accept it by using the following usual selenium alert handle function:
Alert alert=switchTo().alert();
alert.accept();
This can make the test runs well, so it looks I can NOT manually click the alert (after I manually click, the selenium still can NOT go back to the browser...lost connection to browser?), but the automation alert handle code works...
Of course, we want to let user to manually to click alert window to control the test execution, not the automation handle alert.
I really got stuck here for a while, and did a lot googling to search, but can not find similar example online, I hope you can shed me light on it, since you are much more guru than me on JBehave and Selenium.
I will be much grateful if you can help me out.
Selenium is a browser automation tool, it does not anticipate user's interactions.
Therefore, I'd use a simple Java GUI window to present the user with messages/options. Afterall, you are testing a web application in a browser, but the program itself is Java and has nothing to do with the browser. A usual Swing option dialog should be enough.
JOptionPane.showMessageDialog(null, "Login successful.");
String loginAs = JOptionPane.showInputDialog("Login as:", "admin");
int choice = JOptionPane.showConfirmDialog(null, "Use production data?");
(note that you don't want to invoke this in the EventQueue.invokeLater() block, because you want the dialogs to be blocking)
This way, you won't interact with Selenium or the browser in any way, you won't confuse it and you'll get the user input cleanly.
That said, if you insist on using alerts, I think it's definitely doable, but as of now (June 2013, Selenium 2.33.0), I don't know how:
The issue is not reproducible on IE8. After the executeScript("alert('Something.')"); call, Selenium waits for the call to return something and then proceeds normally. So you're good on IE.
However, with FF21, Selenium fails immediatelly with UnhandledAlertException just as you said.
I tried two obvious solutions:
js.executeScript("alert('something')");
new WebDriverWait(driver, 10)
.pollingEvery(100, TimeUnit.MILLISECONDS)
.ignoring(UnhandledAlertException.class)
.until(ExpectedConditions.not(ExpectedConditions.alertIsPresent()))
.wait();
and
js.executeScript("alert('something')");
boolean alertVisible = true;
while (alertVisible) {
try {
driver.switchTo().alert();
} catch (NoAlertPresentException ignored) {
alertVisible = false;
}
}
Both make FF fail horribly with an internal JavaScript exception. Possibly a bug that might get fixed (please test it, check whether it had been reported and report it if you're interested in it), so I'll leave the solutions here for future generations.
But as I said before, it's possible that it won't get fixed, since Selenium doesn't count on manual user interactions.
Not sure how this behaves in other browsers.
I am trying to handle alerts using Selenium Webdriver, according the selenium documentation the correct implementation is:
Alert alert = driver.switchTo().alert();
However I am getting error message The method alert() is undefined for the type WebDriver.TargetLocator
what version of Selenium 2 has this web driver api
Alerts are not be supported by HmltUnit driver. In HtmlUnitDriver.java (Selenium 2.0.6) :
public Alert alert() {
throw new UnsupportedOperationException("alert()");
}
Which driver are you using?
I'm using selenium 2.3 and it works for me. From what I've seen, alerts only work with windows that ONLY have the ok button. Thats where you put the alert.accept(); statement in. Another problem that I've seen with alerts is that it may jump over the alert so you may have to have a wait statement for that specific alert. Hope this helps.
You may need to use a separate import statement for Alert:
import org.openqa.selenium.Alert;
I had the same issue.