Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Alert/Confirm with JavascriptExecutor in Selenium GhostDriver

I'm getting desperate. I'm using Selenium 2.42.2 with the phantomjsDriver 1.1.0 with Java in Eclipse. For my test it is essential that I recognize and store messages of Alerts and Confirms and maybe Prompts when I open a Page. The phantomjsDriver does not implement it yet, so I need a workaround with the JavascriptExecutor. But I am a js noob and can't manage it alone. Here my code and what I tried:

DesiredCapabilities dcaps = new DesiredCapabilities();
String[] phantomArgs = new  String[] {
        "--webdriver-loglevel=NONE"};
dcaps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
dcaps.setCapability(CapabilityType.SUPPORTS_ALERTS, true);
dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, 
        phantomjs.getAbsolutePath());
dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, phantomArgs);
dcaps.setJavascriptEnabled(true);
WebDriver driver = new PhantomJSDriver(dcaps);

JavascriptExecutor js=(JavascriptExecutor) driver;
String script = "window.confirm = function(message) {"+
        "document.lastConfirmationMessage = message; return true; }";
js.executeScript(script);
driver.get("http://www.mysiteWithConfirm.de"); 
Object message = js.executeScript("return document.lastConfirmationMessage");

When I open my site, it opens immediately the Confirm prompt so I know there is a Confirm. But I just get exceptions

Error Message => 'Can't find variable: lastConfirmationMessage'

like image 266
juzwani Avatar asked Dec 30 '25 08:12

juzwani


1 Answers

I don't think there is a way to solve it the way you trying to do it. PhantomJDrvier (GhostDriver) API currently does not yet support alert handling (here is the open issue for in GitHub)

Possible solution to it is to rewrite window.alert so it will output the log to the console. With the ALERT label you can distinguish your alert message log in the console from other logs.

page.evaluate(function() {
    window.alert = function(str) {
        console.log("ALERT:" + str);
    }
});

page.onConsoleMessage(function(message, lineNumber, sourceId) {
    if(/^ALERT:/.test(message)) {
       //do something with message
    }
});

Based my answer on this discussion.

like image 199
Johnny Avatar answered Jan 01 '26 22:01

Johnny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!