I have web-driver test which is stuck because a pop-up window appears. How ca I close it in test?
Here is my code:
#Test
public void canGoToSomePage() throws Exception {
final WebDriver webDriver = getFireFoxDriver();
webDriver.get(getRouteAbsolute("Application.index"));
WebElement someElement = webDriver.findElement(By.id("some_id_here"));
someElement.click();
// HERE I GOT AUTHENTICATION POP-UP I WANT TO CLOSE
assertNotNull(webDriver.findElement(By.id("some_2_id")));
}
Try this,
Alert alert = driver.switchTo().alert();
alert.accept();
I have never used alert before, I used to silent the pop up using JS before. You could do that too, but i guess Alert would be the first choice.
EDIT#1
Here is how to use Java script to silent the pop up. Note that it has to be executed BEFORE the click that causes the popup to show up. Based on whether your pop up is alert, confirm or prompt, you will have to use something like below.
((JavascriptExecutor)driver).executeScript("window.alert = function(msg) { return true; }");
((JavascriptExecutor)driver).executeScript("window.confirm = function(msg) { return true; }");
((JavascriptExecutor)driver).executeScript("window.prompt = function(msg) { return true; }");
Related
How to press the OK button as per the image.
I can switch to this window. but it is not loaded till i click ok, so there is no any elements.
Alert handle does't helped too.
Autoit cannot detect this pop up message too.
disable-notifications cant help too.
Any ideas?
Two screeshots is added.
Firefox snapshot:
Chrome Snapshot:
p.companieGenreal.sActivities().click();
driver.switchTo().defaultContent();
String parent = driver.getWindowHandle();
p.companieGenreal.sAddNew().click();
p.companieGenreal.sAddJobOrder().click();
p.companieGenreal.sContract().click();
swithToChildWindow(parent);
driver.switchTo().alert().accept();
To treat it as an alert try this:
Alert a = driver.switchTo().alert();
a.confirm();
If it can be closed with Escape key, send Escape keypress like this (or ENTER if it closes when Enter is hit):
Actions action = new Actions(driver);
action.sendKeys(Keys.ESCAPE);
beforeunload
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. At this point of time the document is still visible and the event is still cancelable.
Note: Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.
Solution
There are multiple ways to disable this popup as follows:
Firefox: If you are using Firefox as your Browser Client you can use an instance of FirefoxOptions() and set the preference dom.disable_beforeunload to true as follows:
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
FirefoxOptions firefox_option = new FirefoxOptions();
firefox_option.addPreference("dom.disable_beforeunload", true);
WebDriver firefox_driver = new FirefoxDriver(firefox_option);
firefox_driver.get("https://stackoverflow.com/");
Chrome: If you are using Chrome as your Browser Client you can use an instance of ChromeOptions() and add the argument --disable-popup-blocking as follows:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions chrome_option = new ChromeOptions();
chrome_option.addArguments("--disable-popup-blocking");
chrome_option.addArguments("start-maximized");
chrome_option.addArguments("disable-infobars");
WebDriver chrome_driver = new ChromeDriver(chrome_option);
chrome_driver.get("https://stackoverflow.com/");
try using this :
public static void acceptAlertUsingJs(WebDriver driver) {
((JavascriptExecutor)driver).executeScript("window.alert = function(msg){return true;};");
((JavascriptExecutor)driver).executeScript("window.prompt = function(msg) { return true; }");
((JavascriptExecutor)driver).executeScript("window.confirm = function(msg) { return true; }");
}
Please try the below code and see if it helps:
if (isAlertPresent()){
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
}
public static boolean isAlertPresent() {
try {
driver.switchTo().alert();
Thread.sleep(5000);
return true;
}// try
catch (Exception e) {
return false;
}// catch
}
I have the same kind of issue a modal pop up window opens to which i am able to switch to and click the OK button but cannot fetch the text present in it. The modal dialog is shared in the screenshot and has no html tags hence i cannot locate the text in it using any locator. I tried using driver.switchTo().alert().getText() to fetch the text present in it.
If that is an alert you could handle using below methods:
driver.switchTo().alert().accept();
"Actions class":
Actions builder=new Actions(driver);
builder.sendKeys(keys.ESCAPE);
if the above two methods didn't work then there is a special alert type called "sweet alert" which can be inspected and write code for that.
How to handle multiple alert popup confirmation in selenium.
E.g: If accepting popup window, it's asking again and again for the same window. and if that popup closed after clicking 5th time confirmation/dismiss how can we handle the same.
So please help me on this...
If you know the exact number of times this alert will pop up, you can use a simple loop with a hard coded number of retries. For example:
int retries = 5;
while (retries > 0) {
alertTriggerButton.click();
Alert alert = driver.switchTo().alert();
alert.accept();
retries--;
}
You should amend this code to make sure it works according to your page behavior so thinks like response times are taken into account (in other words - add relevant wait times if required).
You can use while. You're checking if the alert is present, and each time it is there, you resolve it according to that boolean value that you give it. When there is no new alert anymore, it will break and continue on.
public static void resolveAllAlerts(WebDriver driver, int timeout, boolean accept) {
while (isAlertPresent(driver, timeout)) {
resolveAlert(driver, accept);
}
}
private static boolean isAlertPresent(WebDriver driver, int timeout) {
try {
Alert a = new WebDriverWait(driver, timeout).until(ExpectedConditions.alertIsPresent());
if (a != null) {
return true;
} else {
throw new TimeoutException();
}
} catch (TimeoutException e) {
// log the exception;
return false;
}
}
private static void resolveAlert(WebDriver driver, boolean accept) {
if (accept) {
driver.switchTo().alert().accept();
} else {
driver.switchTo().alert().dismiss();
}
}
Security warning observed on Firefox:
The information you have entered on this page will be sent over an insecure connection and could be read by a third party.
Are you sure you want to send this information?
Click Continue or cancel
To click on continue I have tried using Robot class method
Robot robot =new Robot();
robot.keyPress(KeyEvent.VK_LEFT);
robot.keyPress(KeyEvent.VK_ENTER);
System.out.println("key pressed");
robot.keyRelease(KeyEvent.VK_ENTER);
But I get UnhandledAlertException: Unexpected modal dialog (text: The information you have entered on this page will be sent over an insecure connection and could be read by a third party.
Are you sure you want to send this information?): The information you have entered on this page will be sent over an insecure connection and could be read by a third party.
Are you sure you want to send this information?
I also tried manually clicking on continue , then continue with selenium script
1 Manually close
2 WebElement success = wait.until(ExpectedConditions
.visibilityOfElementLocated(By.cssSelector(".error-msg")));
Then i get WebDriver exception that ".error-msg" is not a Web Element
Following worked for me in Java
private void acceptSecurityAlert() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(new Function<WebDriver, Alert>() {
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch(NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
}
So I have a method in an automated test, VerifyAndDismissAlert()
try{
WebDriver WD = WebDriver();
Alert alert = WD.switchTo().alert();
alert.accept();
String alertText = alert.getText();
Pause(1);
SeleniumPlus.VerifyValues(AlertTextToVerify, alertText);
} catch (Exception e) {
e.printStackTrace();
}
and when run in Chrome, the alert pops up and dismisses when trying to input in an input box.
In Internet Explorer however, the alert pops up and doesn't dismiss. It seems like the alert isn't even recognized, as when I'm forced to click OK to continue the test, it throws
org.openqa.selenium.NoAlertPresentException: No alert is active
This test works perfectly with the Chrome driver so it has to do something with the IE driver. Any help would be appreciated!
Use ExpectedConditions to wait for alert to be present and you are getting alert.getText() after accepting the alert via alert.accept(); which will sure throw the NoAlertPresentException.Because alert wont be there after accepting. You have do you operations with alert like alert.getText() before accepting or dismissing the alert
WebDriverWait wait = new WebDriverWait(WD, 30);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = WD.switchTo().alert();
String alertText = alert.getText();
System.out.println(alertText);
alert.accept();
My requirement is to give access like one login per user, For that I have updated the login Status to true in db when user login, and false when user logout.
But the problem is when user close the window without logout.
To handle window close I have implemented the following js code
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0;
var leave_message = 'You sure you want to leave?'
function goodbye(e) {
if (!validNavigation) {
if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = leave_message;
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
return leave_message;
}
window.location = "logout.jsp";
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type='button']").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
Here it works for window close, means if user close the window it goes to logout page, but problem is it was going to logout page when user reloads the page.
So I need bind the reload event also like the above js code for f5, submit and anchor tags.
Pleae help me in this regard.
Thanks in Advance...
Two things came into my mind:
First of all the fact that the user is logged in, doesnt mean that theres any activity going on, some people leave there pc turned on with the browser running.
Second is that even if the user closes a page it doesnt necesserly means that he/she wanted to logout and its especially true if the user use two tab to navigate on your site.
So instead of trying to check when they close the tab I suggest considering the idea of logging them out only when they login from somewhere else and/or setting up a timer that automatically log them out after a certain amount of inactivity.