sohaib javed sohaib javed - 11 days ago 12
C# Question

Open link in new tab selenium c#

I am writing a program to run videos listed on my site for testing purpose and here what I need is to run videos in different tabs of the same browser window.

I have hundred video urls in the List

videoLinks = getVideoUrls();

and now what I need is to execute these videos 5 at a time.

ChromeDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.withoutabox.com" + videoLink);


If I go the above way then for all videos I will have to create a new ChromeDriver object. I want to use single chrome browser object.

I have tried this

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


it only adds a new tab but not open a link there.
Please let me know how should I go around it. I have googled but couldn't find my solution so thought to ask for help.

Answer

Try this:

public void SwitchToTab(object pageId)
{
    webDriver.SwitchTo().Window(pageId.ToString());
}

You can use CurrentWindowHandle to find current tab.

webDriver.CurrentWindowHandle;

For your scenario I'm using that code:

public IPageAdapter OpenNewTab(string url)
{
    var windowHandles = webDriver.WindowHandles;
    scriptExecutor.ExecuteScript(string.Format("window.open('{0}', '_blank');", url));
    var newWindowHandles = webDriver.WindowHandles;
    var openedWindowHandle = newWindowHandles.Except(windowHandles).Single();
    webDriver.SwitchTo().Window(openedWindowHandle);
    return new SeleniumPage(webDriver);
}

Update

Window open create new popup. By default this option can be blocked by browser settings. Disable popup blocking in your browser manually.

To check this, open js console in your browser and try to execute command window.open('http://facebook.com', '_blank');

If new window open successfully than everythng is OK.

You can also create your chrome driver with specific setting. Here is my code:

var chromeDriverService = ChromeDriverService.CreateDefaultService();
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("profile.default_content_settings.popups", 0);
return new ChromeDriver(chromeDriverService, chromeOptions, TimeSpan.FromSeconds(150));