PhantomJSDriver Accept Alert

2019-04-08 04:20发布

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();
}

2条回答
聊天终结者
2楼-- · 2019-04-08 04:31

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 :)

查看更多
劳资没心,怎么记你
3楼-- · 2019-04-08 04:47

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();
}
查看更多
登录 后发表回答