How can we switch to new opened tab with webdriver - selenium-webdriver

I have a scenario like when I click on a link it opened in new tab. Using Selenium WebDriver how can we handle it.
As per my knowledge we can't switch to new tab but when I search in Web, got some below solutions.
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
driver.close();
driver.switchTo().window(tabs2.get(0));
Unfortunately, every given solution contains driver.getWindowhandles(). But AFAIK even when a browser has multiple tabs it always returns only one handle.
My scenario is, when I click on one button it opens in new tab.Could any one please provide some solution to
Switch between Tabs or
How to open that tab in new window.

When your new tab has opened,then after that you are in any certain tab of the window.Now, you can use keys.chord(keys.ctrl,keys.tab) for switching between tabs. By using keys, we can take the keyboard i/p.

Write a method to switch the handle of a driver to a new window/tab based on the windows title:
public void SwitchHandleToNewWindow(IWebdriver driver, string windowTitle)
{
ReadOnlyCollection<string> handles = driver.WindowHandles;
foreach(string handle in handles)
{
driver.SwitchTo().Window(handle);
if(driver.Title.Contains(windowTitle))
{
return;
}
}
}
The code is straight forward, so implementation is straightforward too. If you want to switch to a new tab then you do something like : SwitchHandleToNewWindow(driver,"Test Page")

Related

File upload functionality of Selenium web driver for non-input button without AutoIt or Skuliii

I need to upload a document via Selenium WebDriver using Chromedriver. I have tried all the Action class and JavaScript stuff, but those do not work. I am assuming they do not work because those are relying on the button to be an input field, however, the upload button I'm dealing with is not. It's HTML looks like this:
Steps to reproduce:
Go to: https://www.fedex.com/apps/printonline/#!
Click on View Products under Marketing Material
Click on Get Started under Brochure
Click on Use your File to upload the file
Use Your File
I am able to click the use your file button, but I am not sure how I can upload the file.
driver.get("https://www.fedex.com/apps/printonline/#!");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
//Thread.sleep(6000);
if (driver.findElement(By.xpath("//area[#alt='close']")) != null) {
driver.findElement(By.xpath("//area[#alt='close']")).click();
}
driver.findElement(By.xpath("//a[#title='Marketing Materials']/child::button")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//a[#title='Get Started - Brochures']")).click();
Thread.sleep(1000);
WebElement element = driver.findElement(By.xpath("//*[#class='btn fxg-btn-orange mycomputer-upload-link']"));
((JavascriptExecutor)driver).executeScript("arguments[0].click()", element);
Ok so first of all get rid of those Thread.sleep(), use fluent wait with polling time, preferably as a function to locate the elements:
private WebElement waitFor(By locator) {
int timeout = 10;
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.pollingEvery(Duration.ofMillis(200))
.withTimeout(Duration.ofSeconds(timeout))
.ignoring(NoSuchElementException.class);
return wait.until((driver) -> driver.findElement(locator));
}
Then you can click the buttons and upload the file like this:
waitFor(By.cssSelector("button.view-products")).click();
waitFor(By.cssSelector("a.get-started")).click();
waitFor(By.cssSelector("a.get-started")).click();
waitFor(By.cssSelector("input.file-upload")).sendKeys("path_to_my_file");
Notice I am using the input element to upload the file - I am not clicking the a link, as you do not need to do that. Just send the path directly to the input element.

How can I click a web element for a 3rd party page?

I have an Ecommerce website and on one page there is a button named Place Order. When I click on the Place Order button, then it allows me to open a new window named Paypal. I need to stay on the same tab without opening the new window. After that I need to click on the element for that Paypal page.
How can I do this?
My code is as follows:
String parent_handle= driver.getWindowHandle();
System.out.println(parent_handle);
driver.findElement(By.xpath(".//*[#id='co-place-order-area']/div[2]/div[3]/div/button")).click();
new WebDriverWait(driver,10).until(ExpectedConditions.numberOfWindowsToBe(1));
Set<String> handles = driver.getWindowHandles();
System.out.println(handles);
for(String handle1:handles)
if(!parent_handle.equals(handle1))
{
driver.switchTo().window(handle1);
System.out.println(handle1);
}
I don't know about java but in C# you would use PopupWindowFinder class
var target = driver.findElement(By.xpath(".//*[#id='co-place-order-area']/div[2]/div[3]/div/button"));
PopupWindowFinder finder = new PopupWindowFinder(driver);
var parent = driver.CurrentWindowHandle;
string newHandle = finder.Click(target);
driver.SwitchTo().Window(newHandle);
Then after you deal with the new window you can switch back to the parent window.

Selenium webdriver automation, automating context menu options

I am not able to click on any element after doing right click in selenium(Java).
Its just doing a right click and is not clicking of any of the options like open in new tab...Instead its just doing a normal click after doing a right click.Can anyone please help me.Below is my code
System.setProperty("webdriver.chrome.driver","C:\Selenium\chromedriver.exe");
WebDriver wd=new ChromeDriver();
wd.get("http://google.com");
Thread.sleep(3000);
//Point a=wd.findElement(By.linkText("Testing")).getLocation();
WebElement b=wd.findElement(By.linkText("About"));
Actions action=new Actions(wd);
//action.contextClick(b).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
action.moveToElement(b);
Thread.sleep(4000);
//action.contextClick(b);
action.contextClick(b);
action.sendKeys(Keys.ARROW_DOWN).sendKe ys(Keys.ENTER).build().perform();
I have tried via context click and move to element as well but no result.Thanks in advance..
Might be this is what you want:
To select the item from the contextual menu, you have to just move your mouse positions with the use of Key down event like this:-
Actions action= new Actions(driver);
action.contextClick(b).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
Soure: Select an Option from the Right-Click Menu in Selenium Webdriver - Java
As per request in the comments adding alternative way to open a link in new tab.
System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("http://www.google.com/");
WebDriverWait wait = new WebDriverWait(driver, 30);
Thread.sleep(3000);
WebElement b=driver.findElement(By.linkText("About"));
Actions action=new Actions(driver);
action.moveToElement(b).perform();
Thread.sleep(4000);
action.keyDown(Keys.CONTROL);
action.click();
action.keyDown(Keys.CONTROL).build().perform();
//action.sendKeys(Keys.RETURN).perform();
Thread.sleep(4000);
driver.quit();
The build() method is used compile all the listed actions into a single step. We use build() when we are performing sequence of operations. We can directly use perform() if we are performing single action. You can read more about Actions class.
Also, re-iterating that I was unable to find the root of the issue in the limited time I had, so I placed a work around. So like we use the shortcut CTRL+CLICK to open the link in new tab manually, You might need to find out the shortcut for what you need, you can refer this : https://support.google.com/chrome/answer/157179?hl=en
Hope it helps :)

Could not switch between browsers in selenium webdriver

Iam trying to switch between browser ie on click of a button it launches a new browser it
is finding the handle ..the problem is it is not able to find the object inside the new browser searched with id,xpath,name etc can some one give me any suggestion on the same.
also it is able to match the url as well.
please provide me the solution on the same.
below is the code.
//Previous screen
Set windows = driver1.getWindowHandles();
driver1.findElement(By.id("findButton")).click();
//switching handle for the new screen
driver1.switchTo().window("Customer Search");
driver1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
int i = 1;
while(i<= 10){
for (String handle : driver1.getWindowHandles()) {
String myTitle = driver1.switchTo().window(handle).getTitle();
System.out.println("myTitle value : " +myTitle);
//customer search is the new window title
if(myTitle.equalsIgnoreCase("Customer Search")){
driver1.manage().window().maximize();
//if i pass the right url of the screen that is also matching here i have given dummy("sshsj")
if(driver1.getCurrentUrl().equalsIgnoreCase("sshsj"));
{
System.out.println("Url is matching");
//But not able the recognise the object on the new window.
driver1.findElement(By.xpath("html/body/left/form/table/tbody/tr[2]/td[1]/input")).sendKeys("kamal");
}
You can use JS to open a new window, it's faster.
IJavaScriptExecutor jscript = driver as IJavaScriptExecutor;
jscript.ExecuteScript("window.open()");
Then to switch windows, use the window handles:
List<string> handles = driver.WindowHandles.ToList<string>();
driver.SwitchTo().Window(handles.Last());
driver.get(url);
driver.findElement(By.xpath("html/body/left/form/table/tbody/tr[2]/td[1]/input")).sendKeys("kamal");
It is possible that the element may be present inside an iframe. In that case, you need to switch to that iframe before you can access any element inside the iframe.

Launch default web browser, but not if URL already open

I have a link on my app UI that launches a URL using System.Diagnostics.Process.Start(). If the user clicks the link several times, it opens several tabs.
Is there a way, maybe a command-line option, to still use the default web browser, but have it just reopen the same tab if the URL is already open? It would be OK if it doesn't work with every possible browser out there, but nice if it at least works with IE, Firefox and Chrome.
I doubt it, but since I didn't see any other questions/answers on this topic, I figured I'd ask.
This is somewhat of a workaround but it might get you started. I have used the System.Diagnostics.Process.ProcessId.
As an example I have used IE, I will explain later why I did this. The code is just "quick and dirty" but I just made it as proof of concept.
I have created a basic WinForm app with one button that will open google in IE, if it has already been opened by the application it will not be opened again.
I added the System.Diagnostics reference.
public int ProcessID;
public Form1()
{
InitializeComponent();
}
private void MyButton_Click(object sender, EventArgs e)
{
if (ProcessID == null)
{
StartIE();
}
else
{
if (!ProcessIsRunning())
{
StartIE();
}
}
}
private bool ProcessIsRunning()
{
bool ProcessRunning = false;
foreach (Process p in Process.GetProcesses())
{
try
{
if (p.Id == ProcessID)
{
ProcessRunning = true;
}
}
catch { }
}
return ProcessRunning;
}
private void StartIE()
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "iexplore.exe";
proc.StartInfo.Arguments = "http://www.google.be";
proc.Start();
ProcessID = proc.Id;
}
This does not completely do what you requested but it might be a good start. There are a few reasons why I did it this way and what possible options are..
If you would use the url as the Filename, it would indeed open up the webpage in the default browser, it would however not return a processID. This is why the snippet shows usage of IE. (If you would use this option, you could use the System.IO.File.Exists to make sure the desired browser is installed)
If you would like to use this option, you can query the registry to pick up what te default browser is, if you have that you could launch that from the value obtained from the registry. If you then change the process.startinfo.filename to this value, then you will launch the default browser but you will still obtain a processId so this might be the way forward. You can check how to do this over here: http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/b200903e-ce69-4bd4-a436-3e20a7632dc4
Showing the internet window if it would already be opened, can be done by using the SetForegroundWindow property. As this is already documented in this article, I did not add it in this snippet.
I hope this helps to get you on your way.

Resources