PhantomJSDriver Accept Alert

☆樱花仙子☆ 提交于 2019-12-06 02:21:53

问题


How can I accept an alert with PhantomJSDriver in Java? I am trying to do this with YouTube. I can't get it to work.

I've tried using this code to accept on any driver but it doesn't work with PhantomJS.

static void confirmDialog(WebDriver driver) {
    if (driver instanceof PhantomJSDriver) {
        PhantomJSDriver phantom = (PhantomJSDriver) driver;
        phantom.executeScript("window.confirm = function(){return true;}");
        phantom.executeScript("return window.confirm");
    } else driver.switchTo().alert().accept();
}

回答1:


You must execute JS to set the window.alert call to do nothing. You can use this method.

static void confirmDialog(WebDriver driver) {
    if (driver instanceof PhantomJSDriver) {
        PhantomJSDriver phantom = (PhantomJSDriver) driver;
        phantom.executeScript("window.alert = function(){}");
        phantom.executeScript("window.confirm = function(){return true;}");
    } else driver.switchTo().alert().accept();
}



回答2:


JavascriptExecutor worked for me. Just take care that you should execute it before clicking the event which invoke alert.

((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");

Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked

Hope it will help you :)



来源:https://stackoverflow.com/questions/27994845/phantomjsdriver-accept-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!