I am working on a project which includes clicking on a link and that should open in a new tab using webdriver, the problem is
The supposed link is contained in iFrame, soshift+click isn't working
private void openInNewTabAndSwitch(WebElement linkElement) {
// logic of opening in new tab goes here...
Actions newTab = new Actions(driver);
newTab.keyDown(Keys.SHIFT).click(linkElement).keyUp(Keys.SHIFT).build().perform();
Set<String> windowSet = driver.getWindowHandles();
driver.switchTo().window((String) windowSet.toArray()[1]); }
I cannot find the href attribute since some javascript function is opening it using some onClick()
<a onclick="javascript:LinkOccam (this, 'opportunity');">Mednomics Proposition</a>
Problem:-
It simply opens the required page in same tab.
Now, I cannot find anything related to this, please help..!
Other related info
I am using windows 7, Java 8, ChromeDriver
While you click on a WebElement which opens a New TAB you don't need to worry about whether the WebElement is on Top-Level Browsing Context or within an iFrame. Additionally while switching the TAB induce WebDriverWait and switch accordingly. To achieve that you can use the following code block :
private void openInNewTabAndSwitch(WebElement linkElement)
{
String parentTab = driver.getWindowHandle();
Actions newTab = new Actions(driver);
newTab.keyDown(Keys.CONTROL).click(linkElement).keyUp(Keys.CONTROL).build().perform();
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> windowSet = driver.getWindowHandles();
for(String tab:windowSet)
{
if(!parentTab.equalsIgnoreCase(tab))
{
driver.switchTo().window(tab);
//do your work in the newly opened TAB
}
}
}
This is the code that I have written to open a new tab in already opened in Chrome but it is redirecting to the second url in the existing tab only.
I want to open a new tab and load url of 'www.mailinator.com'
System.setProperty("webdriver.chrome.driver","D:\\Vijayalaxmi Testing\\BrowserDrivers\\ChromeDriver\\chromedriver.exe" );
obj=new ChromeDriver();
String baseUrl="https://www.google.co.in/";
obj.get(baseUrl);
obj.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"t");
obj.get("https://www.mailinator.com/");
Can any one help me with this?
You can open new tab with javascript
public void openNewTab() {
((JavascriptExecutor)driver).executeScript("window.open('about:blank','_blank');");
}
If you want to perform operations within new tab you can use:
driver.switchTo().window(); This method accepts String as an argument. Window handle to be exact
You can get all handles like this
driver.getWindowHandles(). This will return you a Set of all handles in the current browser.
In order to switch to newly created tab, iterate through the handles and use switchTo() method like this:
Set<String> handles = driver.getWindowHandles();
String currentWindowHandle = driver.getWindowHandle();
for (String handle : handles) {
if (!currentWindowHandle.equals(handle)) {
driver.switchTo().window(handle);
}
}
WARNING: This might be tricky if you have more than 2 tabs.
use driver.switchTo().window(tabs.get(1)); to open new tab
obj=new ChromeDriver();
String baseUrl="https://www.google.co.in/";
obj.get(baseUrl);
obj.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"t");
ArrayList<String> tabs = new ArrayList<String> (obj.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //switches to new tab
obj.get("https://www.mailinator.com/");
driver.switchTo().window(tabs.get(0)); // switch back to old
I have written two java file to understand how getWindowHandle() method works but i was confused by seeing two different output in two java file
File 1 : WindowHandling.java
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/SeleniumCode/Chapter%203/HTML/Window.html");
String window1 = driver.getWindowHandle();
//System.out.println("First window handle is "+window1);
WebElement link = driver.findElement(By.linkText("Google Search"));
link.click();
Set<String> windowIterator = driver.getWindowHandles();
for(String s:windowIterator)
{
System.out.println(s);
}
O/P :
{c1310e40-aaed-44cf-9581-61f3b84753fa}
{7a99b954-3198-467f-9b49-9bb02e85d5b1}
File 2:WindowHandler.java
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/SeleniumCode/Chapter%203/HTML/Window.html");
String window1 = driver.getWindowHandle();
System.out.println("First Window Handle is: "+window1);
WebDriver popup = null;
WebElement link = driver.findElement(By.linkText("Google Search"));
link.click();
String window2 = driver.getWindowHandle();
System.out.println("Second window handle is "+window2);
driver.switchTo().window(window1);
driver.switchTo().window(window2);
O/P :
First Window Handle is: {478bdad7-e057-4d27-99ec-38db1f020f6d}
Second window handle is {478bdad7-e057-4d27-99ec-38db1f020f6d}
How in first java code two window handle is different and in second java code it is same
link.click() not changes the windows handler. In the first example you enumerated the handlers that driver has (getWindowHandles method). You may go between these handlers using switchTo method. In the second example you receive the handler that uniquely identifies it within this driver instance (getWindowHandle method). Therefore you twice receive the same handler. And you print the handler before switchTo call.
In your first example you use:
Set<String> windowIterator = driver.getWindowHandles(); // plural!
and then you print out their handles in a loop.
In your second example the order of your (only relevant) commands is:
String window1 = driver.getWindowHandle();
System.out.println("First Window Handle is: "+window1);
// some irrelevant code here
String window2 = driver.getWindowHandle();
System.out.println("Second window handle is "+window2);
// more irrelevant code:
driver.switchTo().window(window1);
driver.switchTo().window(window2);
Your problem is that the code is doing what you told it to do, not what you think you told it to do.
Webdriver launches multiple windows after performing click action. I have tried driver.close() but it close the webdriver and test fails.
WebDriver driver = new FirefoxDriver ();
driver.get("http://www.xyz.com/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement page = driver.findElement(By.className("coupon-rows"));
List <WebElement> coupontrigger = page.findElements(By.className("code"));
System.out.println("number of couponsTriggers on carousel = "+ "coupontrigger.size());
for (int j=0; j<=coupontrigger.size(); j++) {
js.executeScript("$('.ccode.coupon-trigger').eq("+j+").click()");
System.out.println(driver.getTitle());
driver.switchTo().defaultContent();
driver.get("http://www.xyz.com/");
page = driver.findElement(By.className("coupon-rows"));
coupontrigger = page.findElements(By.className("code"));
}
}
If I understood your requirement you want to close the other popups rather than the main window. In that case you can do below. Though I am not 100% sure of your requirement.
String mwh=driver.getWindowHandle(); // Get current window handle
Set<String> s=driver.getWindowHandles();
Iterator<String> ite=s.iterator();
String popupHandle = "";
while(ite.hasNext())
{
popupHandle = ite.next().toString();
if(!popupHandle.contains(mwh)) // If not the current window then shift focus and close them
{
driver.switchTo().window(popupHandle);
driver.close();
}
}
driver.switchTo().window(mwh); // finally move control to main window.
You can introduce a helper method which will do that task for you. You just need to find out what your current view is (WebDriver#getWindowHandle will give the one you have focus on) and then just close the rest of the windows.
private String closeAllpreviouslyOpenedWindows() {
String firstWindow = webDriver.getWindowHandle();
Set<String> windows = webDriver.getWindowHandles();
windows.remove(firstWindow);
for (String i : windows) {
webDriver.switchTo().window(i);
webDriver.close();
}
webDriver.switchTo().window(firstWindow);
return firstWindow;
}
I have situation, when click on button opens the new browser window with search results.
Is there any way to connect and focus to new opened browser window?
And work with it, then return back to original(first) window.
You can switch between windows as below:
// Store the current window handle
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
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
// Continue with original browser (first window)
Just to add to the content ...
To go back to the main window(default window) .
use driver.switchTo().defaultContent();
This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
<!--Perform your operation here for new window-->
driver.close(); //closing child window
driver.switchTo().window(parentWindow); //cntrl to parent window
}
}
I use iterator and a while loop to store the various window handles and then switch back and forth.
//Click your link
driver.findElement(By.xpath("xpath")).click();
//Get all the window handles in a set
Set <String> handles =driver.getWindowHandles();
Iterator<String> it = handles.iterator();
//iterate through your windows
while (it.hasNext()){
String parent = it.next();
String newwin = it.next();
driver.switchTo().window(newwin);
//perform actions on new window
driver.close();
driver.switchTo().window(parent);
}
Surya, your way won't work, because of two reasons:
you can't close driver during evaluation of test as it will loose focus, before switching to active element, and you'll get NoSuchWindowException.
if test are run on ChromeDriver you`ll get not a window, but tab on click in your application. As SeleniumDriver can't act with tabs, only switchs between windows, it hangs on click where new tab is being opening, and crashes on timeout.
Modify registry for IE:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main
Right-click → New → String Value → Value name: TabProcGrowth (create if not exist)
TabProcGrowth (right-click) → Modify... → Value data: 0
Source: Selenium WebDriver windows switching issue in Internet Explorer 8-10
For my case, IE began detecting new window handles after the registry edit.
Taken from the MSDN Blog:
Tab Process Growth : Sets the rate at which IE creates New Tab processes.
The "Max-Number" algorithm: This specifies the maximum number of tab processes that may be executed for a single isolation session for a single frame process at a specific mandatory integrity level (MIC). Relative values are:
TabProcGrowth=0 : tabs and frames run within the same process; frames are not unified across MIC levels.
TabProcGrowth =1: all tabs for a given frame process run in a single tab process for a given MIC level.
Source: Opening a New Tab may launch a New Process with Internet Explorer 8.0
Internet Options:
Security → Untick Enable Protected Mode for all zones (Internet,
Local intranet, Trusted sites, Restricted sites)
Advanced → Security → Untick Enable Enhanced Protected Mode
Code:
Browser: IE11 x64 (Zoom: 100%)
OS: Windows 7 x64
Selenium: 3.5.1
WebDriver: IEDriverServer x64 3.5.1
public static String openWindow(WebDriver driver, By by) throws IOException {
String parentHandle = driver.getWindowHandle(); // Save parent window
WebElement clickableElement = driver.findElement(by);
clickableElement.click(); // Open child window
WebDriverWait wait = new WebDriverWait(driver, 10); // Timeout in 10s
boolean isChildWindowOpen = wait.until(ExpectedConditions.numberOfWindowsToBe(2));
if (isChildWindowOpen) {
Set<String> handles = driver.getWindowHandles();
// Switch to child window
for (String handle : handles) {
driver.switchTo().window(handle);
if (!parentHandle.equals(handle)) {
break;
}
}
driver.manage().window().maximize();
}
return parentHandle; // Returns parent window if need to switch back
}
/* How to use method */
String parentHandle = Selenium.openWindow(driver, by);
// Do things in child window
driver.close();
// Return to parent window
driver.switchTo().window(parentHandle);
The above code includes an if-check to make sure you are not switching to the parent window as Set<T> has no guaranteed ordering in Java. WebDriverWait appears to increase the chance of success as supported by below statement.
Quoted from Luke Inman-Semerau: (Developer for Selenium)
The browser may take time to acknowledge the new window, and you may
be falling into your switchTo() loop before the popup window appears.
You automatically assume that the last window returned by
getWindowHandles() will be the last one opened. That's not necessarily
true, as they are not guaranteed to be returned in any order.
Source: Unable to handle a popup in IE,control is not transferring to popup window
Related Posts:
Selenium switching to new Tab in
IE
How to open new tab in IE using selenium (java) and open a url in
that tab (not
window)
You could use:
driver.SwitchTo().Window(WindowName);
Where WindowName is a string representing the name of the window you want to switch focus to. Call this function again with the name of the original window to get back to it when you are done.
main you can do :
String mainTab = page.goToNewTab ();
//do what you want
page.backToMainPage(mainTab);
What you need to have in order to use the main
private static Set<String> windows;
//get all open windows
//return current window
public String initWindows() {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
return driver.getWindowHandle();
}
public String getNewWindow() {
List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
.collect(Collectors.toList());
logger.info(newWindow.get(0));
return newWindow.get(0);
}
public String goToNewTab() {
String startWindow = driver.initWindows();
driver.findElement(By.cssSelector("XX")).click();
String newWindow = driver.getNewWindow();
driver.switchTo().window(newWindow);
return startWindow;
}
public void backToMainPage(String startWindow) {
driver.close();
driver.switchTo().window(startWindow);
}
So the problem with a lot of these solutions is you're assuming the window appears instantly (nothing happens instantly, and things happen significantly less instantly in IE). Also you're assuming that there will only be one window prior to clicking the element, which is not always the case. Also IE will not return the window handles in a predictable order. So I would do the following.
public String clickAndSwitchWindow(WebElement elementToClick, Duration
timeToWaitForWindowToAppear) {
Set<String> priorHandles = _driver.getWindowHandles();
elementToClick.click();
try {
new WebDriverWait(_driver,
timeToWaitForWindowToAppear.getSeconds()).until(
d -> {
Set<String> newHandles = d.getWindowHandles();
if (newHandles.size() > priorHandles.size()) {
for (String newHandle : newHandles) {
if (!priorHandles.contains(newHandle)) {
d.switchTo().window(newHandle);
return true;
}
}
return false;
} else {
return false;
}
});
} catch (Exception e) {
Logging.log_AndFail("Encountered error while switching to new window after clicking element " + elementToClick.toString()
+ " seeing error: \n" + e.getMessage());
}
return _driver.getWindowHandle();
}
This feature works with Selenium 4 and later versions.
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);
// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);
If you have more then one browser (using java 8)
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestLink {
private static Set<String> windows;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/radler/Desktop/myLink.html");
setWindows(driver);
driver.findElement(By.xpath("//body/a")).click();
// get new window
String newWindow = getWindow(driver);
driver.switchTo().window(newWindow);
// Perform the actions on new window
String text = driver.findElement(By.cssSelector(".active")).getText();
System.out.println(text);
driver.close();
// Switch back
driver.switchTo().window(windows.iterator().next());
driver.findElement(By.xpath("//body/a")).click();
}
private static void setWindows(WebDriver driver) {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
}
private static String getWindow(WebDriver driver) {
List<String> newWindow = driver.getWindowHandles().stream()
.filter(n -> windows.contains(n) == false).collect(Collectors.toList());
System.out.println(newWindow.get(0));
return newWindow.get(0);
}
}