Selenium WebDriver: Open new tab instead of a new window - selenium

I am using Selenium WebDriver. Every link is opened in a new browser window. It is not convenient for me. How can I change it so that it opens just in new tab?

Selenium has the ability to switch over tabs now-a-days. The below code1: will work for firefox, code2: for IE and chrome by using Robot class we can do and the control doesnt move automatically to current tab so we need to switch to the current tab by using window handles method. The given below code will work well When we are running individual script but when running as a suite you may feel the pain in performing key board events. In order to avoid that we got to go with other possibility by using user defined javascript method by using javascript executor in selenium-Java.
We can switch between windows and tabs by identifying its name allocated for each and every windows which we open and the name will be in alphanumeric character.
***Code 1***
//First tab(default tab)
driver.navigate().to("http://www.google.com");
driver.manage().window().maximize();
//second tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.navigate().to("https://yahoo.com");
//third tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.navigate().to("http://www.google.com");
//move to very first tab.
driver.findElement(By.cssSelector("body"))
.sendKeys(Keys.CONTROL + "\t");
// To close the current tab.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");
**code 2**
driver.navigate().to("http://www.google.com");
driver.manage().window().maximize();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
Set<String> handles = driver.getWindowHandles();
List<String> handlesList = new ArrayList<String>(handles);
String newTab = handlesList.get(handlesList.size() - 1);
// switch to new tab
driver.switchTo().window(newTab);
driver.get("http://www.yahoo.com");

Selenium has no ability to switch tabs at the moment. Because of this we force the browser to open links in new windows but since we are able to switch windows we force the browser to take the approach. This may be fixed in a later version

If you don't care about switching between tabs, which is a high probability, just use the following options in firefox:
FirefoxOptions options = new FirefoxOptions().addPreference("browser.link.open_newwindow", 3);
WebDriver driver1 = new new FirefoxDriver(options);
As the first link below explains, Selenium wanted to give the ability to users to switch between tabs. The workaround to achieve this was to instruct the browser to open tabs as windows. This however has some undesirable side-efects like:
you have to manually switch to the tab that a link just opened (and use tricks to find which is this tab).
you have to manually switch back to the original tab if you close the current one.
The code above reverts this option for firefox.
Links:
https://github.com/SeleniumHQ/selenium/issues/6865#issuecomment-456698824
https://www.selenium.dev/documentation/webdriver/interactions/windows/#switching-windows-or-tabs
http://kb.mozillazine.org/Browser.link.open_newwindow

Related

Windows vs tabs in Selenium

As per Difference between webdriver.Dispose(), .Close() and .Quit()
driver.close closes the current active window where driver.quit closes all of the windows. What I get is if I opened a new tab in my current window and then called driver.close the whole windows including my tabs would close. But when I run that code
driver.get("http://testingpool.com/selenium-ide-part-1/");
driver.findElement(By.xpath("//*[#id='content']/div[2]/article/div/div[2]/div[1]/p[8]/span/a")).click(); //opens a new tab
ArrayList<String> allWindowHandles = new ArrayList<> (driver.getWindowHandles());
driver.close()
only the first tabs gets closed. Also I find that my allWindowHandles has length of 2 although I have only one window.
I was trying to open a new window using Selenium as per https://www.tutorialspoint.com/how-to-open-a-new-window-on-a-browser-using-selenium-webdriver-for-python using
((JavascriptExecutor)driver).executeScript("window.open('')");
but that resulted in a new tab not a new window.
I am confused if Selenium differentiates between a tab and a window at all or not.
With the terminology used to distinguish between driver.close() and driver.quit() methods supported by Selenium WebDriver in the post you are referencing to, they actually mostly mean browser tabs, not windows.
By opening a new browser window with
((JavascriptExecutor)driver).executeScript("window.open('')");
or by clicking on some web element opening a new browser tab/window is will normally open a new tab in the existing browser.
What I get is if I opened a new tab in my current window and then
called driver.close the whole window including my tabs would close.
But when I run that code
See you may have opened a new tab by clicking on link or using JavascriptExecutor but Selenium still has focus on first tab of the first window.
Therefore, when you do this:
ArrayList<String> allWindowHandles = new ArrayList<> (driver.getWindowHandles());
driver.close()
It should close the first tab or window, since you have not switched to new tab/window.
Also I find that my allWindowHandles has length of 2
this is cause you have opened a new tab using this line
driver.findElement(By.xpath("//*[#id='content']/div[2]/article/div/div[2]/div[1]/p[8]/span/a")).click(); //opens a new tab
the moment you open a new tab by clicking on a link or Using JavascriptExecutor, you will have +1 windows handle.
However, if you do not switch to any tab or window/s. Selenium will always have focus on first tab of the first window.
Also, window.open('') is Js command not Selenium.
there is a difference between a new tab or windows. But if you take Selenium into consideration, We switch to new tab or windows in a same way.
However to open a new window, you would have to simulate CTRL+N keyboard action.

IWebDriver opens a blank data window after clicking on button instead of the loaded content that suppose to be - selenium c#

I have selenium.support version 3.141.0, chrome driver version 2.43.0 and Google Chrome version 71.0.3578.98 and Selenium.ChromeDriver.dll 2.43.0.
when i click on a certain button a new window should be open. i click on the button and if i use any action on the browser for example new WebDriverWait(_driver, TimeSpan.FromSeconds(60)).Until(IsPageLoaded); the window stop to load and stay blank data. why can't i get the browser to load it's content?
Edit: when the new window opens i change the the driver to the latest windowHandel and use the webDriverWait from above to wait which result in a blank data window, but if i use thread.sleep after changing the windowHandel the window load its content
You can try with a explicit wait for a element to be visible on the new window. That would ensure it waits for the contents to load up

Selecting right click option from context menu in selenium

I have a scenario where i need to right click on a link, when context menu appears i need to click on option "Open link in incognito window".
When i try to achieve this by below code snippet i could see a context menu appears but instead of launching the link in new window the link gets launched in same window.
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.google.com/");
Actions action = new Actions(driver);
WebElement ele = driver.findElement(By.linkText("About"));
action.contextClick(ele).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
any suggestions how to make this happen?
There may be a keyboard shortcut for opening a link in an incognito window but I was unable to find one but I didn't look for long. You may have better luck.
Another method would be to grab the URL of the link you want to click, open an incognito window using the keyboard shortcut (CTRL+SHIFT+N), and then navigating to the URL. It's not ideal but I don't know of another way to do this.
Is there some reason you can't just start your script in an incognito window and proceed from there?
This context menu is not a part of html page, but this is a menu coming from Chrome (a desktop application)
Selenium/WebDriver does not have the capability to automate the desktop applications, you can use AutoIt or similar software to do it
But all what you need is just to open a new browser session (incognito window is nothing but a new, independent browser session).
To simulate this behaviour using WebDriver just open a new Chrome driver:
WebDriver drv1 = new ChromeDriver();
drv1.get("https://www.google.pl");
drv1.findElement(By.name("q")).sendKeys("About");
........
........
// This will open a new browser window with a new, independent browser session
WebDriver drv2 = new ChromeDriver();
drv2.get("https://www.google.pl");
drv2.findElement(By.name("q")).sendKeys("Hello");
........
........
drv1.do-Something-in-session-1
.....
drv2.do-Something-other-in-session-2
....

Shifting focus to another window before page loads

I'm using selenium testng format for testing my UI. I want to shift my focus from my main window to another window, where i click on a link before the page on my main window has finished loading.
Clicking an Element on page load is even possible on webdriver; By default, webdriver wait for the entire page to load and then picks the element. The links and texts are visible but they are not clickable; However, it works well on Selenium IDE picking elements on page load.
I hope the below Firefox profile will help you to do the same for switching windows.
Webdriver make use of the FirefoxProfile to avoid such risks; It's applicable only for Firefox browser.
FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("webdriver.load.strategy", "unstable");
driver = new FirefoxDriver(fp);
Well i found a way around my problem. Instead of trying to shift the focus from one page to another i just ran the tests parallel to each other.
For more info you can check this link: (http://blog.wedoqa.com/2013/07/how-to-run-parallel-tests-with-selenium-webdriver-and-testng-2/)

Robot Framework verify a new browser tab was opened

For some of the web links on our page, there are external links which direct the user to say Facebook and Twitter. The links use the HMTL tag target="_blank" so that a new browser tab is opened for our Twitter page.
I would like to verify 1. the new browser tab is open, 2. set focus to it and 3. validate page elements in the new browser tab. The #3 part would be easy enough, once I get focus on it. Tasks #1 and #2 though, I can't figure out, nor can I find anyone talking about this.
Using Selenium2Library (WebDriver)
Selenium does not support tabs (as of June 2013, Selenium 2.33.0) and always opens new windows instead. If your test opens a new tab, good luck to you.
That said, if it correctly opens a new window, use Select Window.
Select Window | url=https://twitter.com/expectedPage
My working WebDriver (2.33.0) code in Java, hopefully it will help a little. The problems you are describing are where my Robot knowledge begins to fall off.
#Test
public void targetBlankLinkTest() {
// load the website and make sure only one window is opened
driver.get(file("TargetBlankLinkTest.html"));
assertEquals(1, driver.getWindowHandles().size());
// click the link and assert that a new window has been opened
driver.findElement(By.linkText("Follow us on Twitter!")).click();
Set<String> windowHandles = driver.getWindowHandles();
assertEquals(2, windowHandles.size());
// switch to the new window and do whatever you like
// (Java doesn't have Switch Window functionality that can select by URL.
// I could write it, but have been using this trick instead)
for (String handle : windowHandles) {
if (handle != driver.getWindowHandle()) {
driver.switchTo().window(handle);
}
}
assertThat(driver.getCurrentUrl(), containsString("twitter.com"));
}
if you want to verify if a new tab has opened or not then you can just compare the window handles before and after clicking a link/element which opens a new tab. Just follow this code might help you.
Here ${LINKDIN} is the element which opens in new tab. so before clicking on it save the window handles in variable and after clicking the element again save the window handle in a variable. now if a new is tab is opened then both the variable value will be different and if no new tab is opened then both variable value is same.in this way you can verify the ne wtab opening.
Go Back
${Current_window} List Windows
Click Element ${LINKDIN}
${New_Windows_list} List Windows
Should Not Be Equal ${Current_window} ${New_Windows_list}
Using Robot Selenium2Library keywords :
#{windows} = List Windows
${numWindows} = Get Length ${windows}
${indexLast} = Evaluate ${numWindows}-1
Should Be True ${numWindows} > 1
Select Window #{windows}[${indexLast}]
Location Should Contain /my/url/whatever
Title Should Be myTitle
Page Should Contain ...
You get the idea.
I recommend:
1. First, acquire new window handle by using the switchTo() method.
2. Then bring that window into focus using a JavaScriptExecutor:
((JavascriptExecutor) myTestDriver).executeScript("window.focus();");
Using switchTo() without a javascript executor to get focus , is not
very reliable in my opinion.
3. Next, do what you need to do in that window.
4. Use driver.close() to close that window.
5. Verify you are back at the parent window with focus.
U can use below code to set focus on new window:
Click element ${a_link_which_opensin_newtab}
Select window New
now u can perform your actions on new tab. If u want to switch back the main tab then use
Select window Main