Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJSDriver Accept Alert

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();
}
like image 607
Jire Avatar asked Jan 17 '15 00:01

Jire


2 Answers

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();
}
like image 128
Jire Avatar answered Oct 06 '22 00:10

Jire


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

like image 22
Shubham Jain Avatar answered Oct 05 '22 23:10

Shubham Jain