简体   繁体   中英

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.

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));

Here is a simple solution for open a new tab in seleneium c#:

driver.Url = "http://www.gmail.net";
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.open();");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM