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();
}
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();
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With