3

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'

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
juzwani
  • 53
  • 2
  • 7

1 Answers1

2

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.

Community
  • 1
  • 1
Johnny
  • 14,397
  • 15
  • 77
  • 118