How to handle browser notification popup which is without any elements? - java

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.

Related

How to handle multiple windows in selenium?

While automating via Selenium WebDriver, I have the below scenario. On a window, I copy the link and want to open the link on the new window(not in the new tab) and want to set focus on the new window. (Here the second window is not the child window of the first window)please help
You can do something like this
WebDriver driverOne=new ChromeDriver();
// navigate to your desired URL
driverOne.get("http://www.yourwebsite.com/");
// Do your stuff and copy the new link
// string newURL;
WebDriver driverSecond=new ChromeDriver();
driverSecond.get(newURL);
driverSecond will have a focus on the new window and once your actions are complete close the driverSecond.
In Selenium 4 (currently in beta), you the following will open a new window then automatically switch to the window:
#Test
public void openNewWindowForTestProjectBlog () {
WebDriver newWindow = driver.switchTo().newWindow(WindowType.WINDOW);
newWindow.get("https://blog.testproject.io/");
System.out.println(driver.getTitle());
}
//assume - multiple windows are opened by clicking link or a button.
Set<String> windows = driver.getWindowHandles();
for (String window : windows)
{
if (driver.getTitle().contains("***Something that is on new window***"))
{
driver.switchTo().window(window);
//To get title of new window
System.out.println(driver.switchTo().window(window).getTitle());
}
}

driver.close() terminates the test

I use selenium WebDriver. I am trying to run following scenario.
I launch a url, and I want to add a condition that if there is any url opened other than the one I intended, I want to close it.
Following is my code, I will explain whats happening with it below.
if (config.getProperty("browser").equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
selectServer();
String currentURL = driver.getCurrentUrl();
if (currentURL != config.getProperty("production") || currentURL != config.getProperty("staging") || currentURL != config.getProperty("development"))
{
Thread.Sleep(10000); //for Debugging purpose
driver.close();
}
}
I have a config.properties file where I set the browser / server selection.
Now what happens is, when I launch the test, chrome launches and:
Chrome settings window opens and it asks me to restore default settings. (Window in display)
My intended URL opens up. (hidden)
When I run the test, the test passes but Chrome Settings window does not close. I tried to print the current URL , and it returns the production server URL which is my intended URL but the browser window in display is not my production URL.
Based on your response in comments, I believe you need to switch to the settings tab, close that tab, then switch back to the original tab. The below code should do that:
public static void closeBrowserTab() {
String originalHandle = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
driver.switchTo().window(handle);
driver.close();
break;
}
}
driver.switchTo().window(originalHandle);
}

Handle firefox security warning in selenium web driver

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

How to close child browser window in Selenium WebDriver using Java

After I switch to a new window and complete the task, I want to close that new window and switch to the old window,
so here i written like code:
// Perform the click operation that opens new window
String winHandleBefore = driver.getWindowHandle();
// Switch to new window opened
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
driver.findElement(By.id("edit-name")).clear();
WebElement userName = driver.findElement(By.id("edit-name"));
userName.clear();
try
{
driver.quit();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("not close");
}
driver.switchTo().window(winHandleBefore);// Again I want to start code this old window
Above I written code driver.quit() or driver.close(). But I am getting error. Can anybody help me...?
org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.
To close a single browser window:
driver.close();
To close all (parent+child) browser windows and end the whole session:
driver.quit();
The logic you've used for switching the control to popup is wrong
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
How the above logic will swtich the control to new window ?
Use below logic to switch the control to new window
// get all the window handles before the popup window appears
Set beforePopup = driver.getWindowHandles();
// click the link which creates the popup window
driver.findElement(by).click();
// get all the window handles after the popup window appears
Set afterPopup = driver.getWindowHandles();
// remove all the handles from before the popup window appears
afterPopup.removeAll(beforePopup);
// there should be only one window handle left
if(afterPopup.size() == 1) {
driver.switchTo().window((String)afterPopup.toArray()[0]);
}
// Perform the actions on new window
**`//Close the new window`**
driver.close();
//perform remain operations in main window
//close entire webDriver session
driver.quit();
//store instance of main window first using below code
String winHandleBefore = driver.getWindowHandle();
Perform the click operation that opens new window
//Switch to new window opened
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
driver.close(); //this will close new opened window
//switch back to main window using this code
driver.switchTo().window(winHandleBefore);
// perform operation then close and quit
driver.close();
driver.quit();
There are 2 ways to close the single child window:
Way 1:
driver.close();
Way 2: By using Ctrl+w keys from keyboard:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");
I've also tried
1)driver.close();
2)driver.quit();
apparently, these methods don't work as expected!(not saying it don't work though) I've even tried making the driver class singleton and it didn't help me with running test cases parallel.so it was also not the optimal solution.finally, i came up creating a separate class to run a bat file.which the bat file contains commands of grouping all the chrome driver process and all the child processes of it.and from the java class I've executed it using Runtime.
The class file that runs the bat file
public class KillChromeDrivers {
public static void main(String args[]) {
try {
Runtime.getRuntime().exec("cmd /c start E:\\Work_Folder\\SelTools\\KillDrivers.bat");
//Runtime.getRuntime().exec()
} catch (Exception ex) {
}
}
}
The command that you have to put in the [ .bat ] file
taskkill /IM "chromedriver.exe" /T /F
There are some instances where a window will close itself after a valid window handle has been obtained from getWindowHandle() or getWindowHandles().
There is even a possibility that a window will close itself while getWindowHandles() is running, unless you create some critical section type code (ie freeze the browser while running the test code, until all window management operations are complete)
A quicker way to check the validity of the current driver is to check the sessionId, which is made null by driver.close() or by the window closing itself.
The WebDriver needs to be cast to the remote driver interface (RemoteWebDriver) in order to obtain the sessionId, as follows:
if (null == ((RemoteWebDriver)driver).sessionId) {
// current window is closed, switch to another or quit
} else {
// current window is open, send commands or close
}
Also note that closing the last window is equivalent to quit().
public class First {
public static void main(String[] args) {
System.out.println("Welcome to Selenium");
WebDriver wd= new FirefoxDriver();
wd.manage().window().maximize();
wd.get("http://opensource.demo.orangehrmlive.com/");
wd.findElement(By.id("txtUsername")).sendKeys("Admin");
wd.findElement(By.id("txtPassword")).sendKeys("admin");
wd.findElement(By.id("btnLogin")).submit();
**wd.quit(); //--> this helps to close the web window automatically**
System.out.println("Tested Sucessfully ");
}
}

WebDriver closing the popup

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

Categories