How to handle / receive JS alerts in PhantomJS using WebDriver?

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

I found the JSPhantom onAlert documentation , but no matter what the equivalent PhantomJSDriver code for

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

to be?

I am currently returning earlier with a guard for clause PhantomJSDriverto stop exceptions, but how should js warnings work in PhantomJS with?

+4
source share
2 answers

I had similar problems with the PhantomJS Web Driver handlers. This code seems to resolve the issue. This is a C # implementation, but should also work with Java.

      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;
                }
            }
Hide result

,

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

PhantomJS Alerts accept.

+7

, PhantomJS .

( Python/Splinter), , .

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

.

+3

Source: https://habr.com/ru/post/1584229/


All Articles