Handling alerts using HtmlUnitDriver in Java
Asked Answered
D

2

6

I want to handle alerts Using HTMLUnitDriver in java. I am using following code to handle the alerts using firefox driver and it is working fine.

Alert alert = driver.switchTo().alert();
alert.accept();

but HTMLUnitDriver is giving error like

java.lang.UnsupportedOperationException: alert() 

How to handle there alert box ?

Dropsonde answered 15/5, 2014 at 10:30 Comment(0)
W
0

If you don't need to check whether the alert actually appears, I would recommend changing the behavior of the JavaScript alert() method to log a message instead:

JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
javascriptExecutor.executeScript("window.alert = function(message){ console.log(message); };" +
    "window.confirm = function(message){ console.log(message); return true; };");

Then you can skip HtmlUnitDriver.switchTo().alert().accept() in your code.

Note: This method won't work if the alert appears on the initial page load since Selenium waits for the page to be loaded before interacting with it. So the above JavaScript will be executed too late.


As of HtmlUnitDriver version 2.25, HtmlUnitDriver.switchTo().alert().accept() no longer throws an UnsupportedOperationException(). However, accept() appears to do nothing except confirm that the alert is present. Since the alert cannot be dismissed, turning off alerts using the above method is probably the best/only solution. If you must test alerts with HtmlUnitDriver, you may need two separate tests---one for checking that the alert appears and another for checking that the browser behaves correctly when the alert is disabled.


If you desperately need alert handing and you are okay with building from source, alert handling has been implemented in the master branch of HtmlUnitDriver. I'm not sure when it will be included in a release, though.

Weisbrodt answered 10/3, 2017 at 3:40 Comment(0)
M
-1

The request to implement the alert-API in the HTMLUnitDriver has been placed several years ago. This is the link:

https://code.google.com/p/selenium/issues/detail?id=1105&q=alert%28%29&colspec=ID%20Stars%20Type%20Status%20Priority%20Milestone%20Owner%20Summary

As this seems to be a hard nut to crack, you have to think about some tricks to circumvent the modal dialogs (alert, confirm, ...) in JavaScript. At least until they have implemented the alert-API.

The tricks to prevent the modal dialogs to show consists of adding additional JavaScript to your Selenium script. For example change the callback-functions to avoid the alert box.

Also, be aware it is impossible to close/cancel/confirm modal dialogs with JavaScript itself. That's the reason why you should prevent them to show. This is due to security reasons.

Until the alert-API has been implemented, this is the only way to handle it with HtmlUnitDriver.

Mendelsohn answered 1/6, 2015 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.