-1

Code language c# Selenium Webdriver

I'm trying to open in chrome a new tab with the following code:

        Actions action = new Actions(BrowserFactory.Driver);
        action.SendKeys(Keys.Control + "T").Build().Perform();
        string secondTabHandle = BrowserFactory.Driver.CurrentWindowHandle;

I found this code on stackoverflow.

I also tried:

        IWebElement body = 
        BrowserFactory.Driver.FindElement(By.TagName("body"));
        body.SendKeys(Keys.Control+'t');
        body.SendKeys(Keys.Control+"t");

Thats also not working

Nothing happens after using this code.

Can someone help me what I am doing wrong.

Thanks in advance.

3
  • 1
    Possible duplicate of How to open a new tab using Selenium WebDriver with Java? Commented Sep 12, 2017 at 9:57
  • Ignore the fact it's Java, just as relevant to c# Commented Sep 12, 2017 at 9:57
  • I also tried IWebElement body = BrowserFactory.Driver.FindElement(By.TagName("body")); body.SendKeys(Keys.Control + 't'); As explained on that page but that doesnt do anything Commented Sep 12, 2017 at 10:06

1 Answer 1

1

The better solution is not dependent press CTRL+T or whatever, because on different browser or different version on same brower, the CTRL+T may lead to different behaviour.

I prefer the solution to execute javascript on browser to open a new tab, becasuse inject and execute javascript on browser supported natively by selenium.

We should make the javascript do following things on browser:

  1. create a link node, and set the link href is 'about:blank' or the url you want to open, set the link target is '_blank'

  2. append the link node to body of current opening page

  3. click the link and remove the link from body

code example:

string newTabScript = "var d=document,a=d.createElement('a');"
+ "a.target='_blank';a.href='{0}';"
+ "a.innerHTML='new tab';"
+ "d.body.appendChild(a);"
+ "a.click();"
+ "a.parentNode.removeChild(a);"

public void newTab(string tabUrl) 
{
  if(String.IsNullOrEmpty(tabUrl) {
    tabUrl = "about:blank";
  } 
  IWebDriver driver; // assume assigned elsewhere
  IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
  js.ExecuteScript(String.format(newTabScript, tabUrl));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Do you also have a code for switching between tabs?
For chrome browser, you can try as binaryclips.com/2016/03/… said, a reminder after swtich, you may noticed the active Tab not changed, but indeed the script to operate on the switched Tab should work.
@Yong how would you do for new browser (not new tab)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.