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());
}
}
Related
I am unable to focus on newly open window using selenium and java.
I am using Internet explorer for running my application.
The new window is opening but not able to perform anything on the new window.
I tried with
Set<String> allwindows = driver.getWindowHandles();
but still issue is not resolved.
Below is the code I am using .
driver.get("www.tririga.com");
String parentwindow=driver.getWindowHandle();
driver.findElement(By.id("login")).click();
for(String childwindow: driver.getWindowHandles()) {
driver.switchto().window(childwindow);
driver.findElement(By.id("submit")).click();
driver.close();
}
driver.switchto().window(parentwindow);
driver.close();
You need to check that you are not using the first window handle to switch. You can also wait for the new window to open with explicit wait
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.findElement(By.id("login")).click();
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
for(String childwindow: driver.getWindowHandles()) {
if (!childwindow.equals(parentwindow)) {
driver.switchto().window(childwindow);
driver.findElement(By.id("submit")).click();
driver.close();
}
}
driver.switchto().window(parentwindow);
driver.close();
If this is the end of your code and you just want to close all the windows just use quit()
Quits this driver, closing every associated window.
for(String childwindow: driver.getWindowHandles()) {
if (!childwindow.equals(parentwindow)) {
driver.switchto().window(childwindow);
driver.findElement(By.id("submit")).click();
}
}
driver.quit();
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.
I am trying to automate Goibibo Website in Selenium using Java. After Clicking on Sign in Tab, login pop up is displaying. How to switch to pop up so that I can enter details into the Goibibo Pop up. I wrote the following code:
public class Testclass1 {
public static void main(String[] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver", "D://chromedriver_win32//chromedriver.exe");
WebDriver Driver = new ChromeDriver();
Driver.manage().window().maximize();
Driver.get("https://www.goibibo.com/");
Thread.sleep(5000);
//HANDLE THE POP UP
String handle = Driver.getWindowHandle();
System.out.println(handle);
// Click on the Button "New Message Window"
Driver.findElement(By.linkText("Sign In")).click();
Thread.sleep(3000);
// Store and Print the name of all the windows open
Set handles = Driver.getWindowHandles();
System.out.println(handles);
// Pass a window handle to the other window
for (String handle1 : Driver.getWindowHandles()) {
System.out.println(handle1);
Driver.switchTo().window(handle1);
}
Thread.sleep(3000);
Driver.findElement(By.name("username")).sendKeys("bittu.agrawal773#gmail.com");
//WAIT
}
}
Opened popup is not a new window popup, it's just simple HTML login popup present is iframe which can be simply handled by switching to iframe as below working code :-
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
driver.get("https://www.goibibo.com/");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Sign In"))).click();
//switch to popup iframe to enter login credentials into form
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("authiframe"));
//now enter login credentials
driver.findElement(By.id("id_username")).sendKeys("username");
driver.findElement(By.id("id_password")).sendKeys("password");
//now click on sign in button
driver.findElement(By.id("signinBtn")).click();
Note:- For better way, you should use WebDriverWait to wait explicitly for element with certain ExpectedConditions instead of Thread.sleep().
So after my code runs a new window shows up to download a CSV. A window pops up to either save the file or to open it with excel. How would I change windows to download that csv to a path using selenium.
public class automation {
public static void main(String[] args) {
FirefoxProfile profile = new FirefoxProfile();
String path = "C:\\Users\\K344975\\Desktop";
profile.setPreference("browser.download.dir",path);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/xls;text/csv");
profile.setPreference("plugin.disable_full_page_plugin_for_types",
"application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;application/xls;");
WebDriver driver = new FirefoxDriver(profile);
driver.get("");
String winHandle = driver.getWindowHandle();
System.out.println(winHandle);
//driver.quit();
}
}
I also tried making a profile
Well you have firstly patch profile and only after it create browser, and for plugin disable you could use
profile.setPreference("plugin.disable_full_page_plugin_for_types",
"application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;")
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 ");
}
}