Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium ChromeDriver switch tabs

When I click on a link in my test, it opens a new tab. I want ChromeDriver to then focus on that tab. I have tried the following code to get ChromeDriver to change tabas using the ctrl+tab shortcut:

Actions builder = new Actions(driver);
builder.KeyDown(Keys.Control).KeyDown(Keys.Tab).KeyUp(Keys.Tab).KeyUp(Keys.Control);//switch tabs
IAction switchTabs = builder.Build();
switchTabs.Perform();

But this throws the following exception:

ekmLiveChat.tests.UITests.EndToEndTest.EndToEnd:
System.ArgumentException : key must be a modifier key (Keys.Shift, Keys.Control, or Keys.Alt)
Parameter name: key

Is there a way to switch tabs using ChromeDriver?

like image 472
Lisa Young Avatar asked May 11 '12 10:05

Lisa Young


People also ask

Can we switch tab in Selenium?

We can switch tabs using Selenium. First we have to open a link in a new tab. The Keys. chord method along with sendKeys is to be used.

How do I switch to the active tab in Selenium?

To switch the focus to the new tab, switchTo(). window method is used. The getWindowHandle method is used to hold the window id of the active tab and it is then passed as parameter to the switchTo().

How do I switch between multiple windows in Selenium?

In Selenium, when we have multiple windows in any web application, the approach may need to switch control among several windows i.e from one window to another to perform any action and we can achieve this by using switchto(); method.


2 Answers

As mentioned in my comment on your post, I'm not sure if the Chrome driver handles tabs the same way as it handles windows.

This code works in Firefox when opening new windows, so hopefully it works in your case as well:

public void SwitchToWindow(Expression<Func<IWebDriver, bool>> predicateExp)
{
    var predicate = predicateExp.Compile();
    foreach (var handle in driver.WindowHandles)
    {
        driver.SwitchTo().Window(handle);
        if (predicate(driver))
        {
            return;
        }
    }

    throw new ArgumentException(string.Format("Unable to find window with condition: '{0}'", predicateExp.Body));
}

SwitchToWindow(driver => driver.Title == "Title of your new tab");

(I hope my edits to the code for this answer didn't introduce any errors...)

Just make sure you don't start looking for the new tab before Chrome has had the chance to open it :)

like image 193
Torbjörn Kalin Avatar answered Oct 29 '22 23:10

Torbjörn Kalin


This is what worked for me:

var popup = driver.WindowHandles[1]; // handler for the new tab
Assert.IsTrue(!string.IsNullOrEmpty(popup)); // tab was opened
Assert.AreEqual(driver.SwitchTo().Window(popup).Url, "http://blah"); // url is OK  
driver.SwitchTo().Window(driver.WindowHandles[1]).Close(); // close the tab
driver.SwitchTo().Window(driver.WindowHandles[0]); // get back to the main window
like image 20
DevDav Avatar answered Oct 29 '22 22:10

DevDav