4

Being new to PhantomJSDriver for Selenium, how does it handle JS alerts?

I've found the JSPhantom onAlert documentation, but what would the equivalent PhantomJSDriver code for

Driver.SwitchTo().Alert().Accept();

be?

At the moment, I've returning early with a guard clause for PhantomJSDriver, to stop exceptions, but how should js alerts in PhantomJS be interacted with?

Community
  • 1
  • 1
StuperUser
  • 10,555
  • 13
  • 78
  • 137
  • 1
    I dont think Ghostdriver supports alert handling. See this - https://github.com/detro/ghostdriver/issues/20. See this question - http://stackoverflow.com/questions/15708518/how-can-i-handle-an-alert-with-ghostdriver-via-python – LittlePanda Apr 23 '15 at 11:46

2 Answers2

7

I had similar problems with PhantomJS Web Driver handling alerts. The below code seems to resolve the issue. This is a C# implementation but should work with Java too..

      public IAlert GetSeleniumAlert()
            {
                //Don't handle Alerts using .SwitchTo() for PhantomJS
                if (webdriver is PhantomJSDriver)
                {
                  var js = webdriver as IJavaScriptExecutor;

                 
                  var result = js.ExecuteScript("window.confirm = function(){return true;}") as string;
                    
                  ((PhantomJSDriver)webdriver).ExecutePhantomJS("var page = this;" +
                                                 "page.onConfirm = function(msg) {" +
                                                 "console.log('CONFIRM: ' + msg);return true;" +
                                                    "};");
                  return null;
                }

                try
                {
                    return webdriver.SwitchTo().Alert();
                }
                catch (NoAlertPresentException)
                {
                    return null;
                }
            }

And later in the code where you expect Alerts to occur

IAlert potentialAlert = GetSeleniumAlert();
                if (potentialAlert != null) //will always be null for PhantomJS
                {
                    //code to handle Alerts
                    IAlert alert=webDriver.SwitchTo().Alert();
                    alert.Accept();
                }

For PhantomJS, we are setting the default response to Alerts as accept.

JSDeveloper
  • 178
  • 8
3

I don't think PhantomJS currently supports alert handling.

To simply accept alerts, (in Python/Splinter) try this for every reloaded page that would have an alert later.

driver.execute_script("window.confirm = function(){return true;}");

See more reference here.

Yuxiang
  • 349
  • 3
  • 3