-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.

xxx2017
  • 207
  • 1
  • 5
  • 15
  • 1
    Possible duplicate of [How to open a new tab using Selenium WebDriver with Java?](https://stackoverflow.com/questions/17547473/how-to-open-a-new-tab-using-selenium-webdriver-with-java) – Liam Sep 12 '17 at 09:57
  • Ignore the fact it's Java, just as relevant to c# – Liam Sep 12 '17 at 09: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 – xxx2017 Sep 12 '17 at 10:06

1 Answers1

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));
}
yong
  • 13,357
  • 1
  • 16
  • 27
  • Do you also have a code for switching between tabs? – xxx2017 Sep 12 '17 at 11:51
  • For chrome browser, you can try as http://www.binaryclips.com/2016/03/selenium-webdriver-in-c-switch-to-new.html 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 Sep 12 '17 at 12:51
  • @Yong how would you do for new browser (not new tab) – Ashok kumar Ganesan Apr 08 '20 at 09:53