Open a new tab in an existing browser session using Selenium

后端 未结 5 667
一个人的身影
一个人的身影 2020-12-28 21:01

My current code below in C# opens a window then navigates to the specified URL after a button click.

protected void onboardButton_Click(object sender, EventA         


        
相关标签:
5条回答
  • 2020-12-28 21:05
    IWebDriver driver = new ChromeDriver(); 
    

    Change this to:

    var driver = new ChromeDriver();
    

    I do not know why. May be the IWebDriver miss the method.

    0 讨论(0)
  • 2020-12-28 21:08

    This may not works:

    driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
    

    Alternative: Find clickable element with target blank (search for "blank" in page's surce code). This will open new tab.

    Than switch between tabs (thanks @Andersson) with:

    driver.SwitchTo().Window(driver.WindowHandles.Last());
    driver.SwitchTo().Window(driver.WindowHandles.First());
    
    0 讨论(0)
  • 2020-12-28 21:10

    Sending Keys.Control + "t" didn't work for me. I had to do it with javascript and then switch to it.

    ((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
    driver.SwitchTo().Window(driver.WindowHandles.Last());
    
    0 讨论(0)
  • 2020-12-28 21:25

    To handle new tab you should switch to it first. Try following:

    driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
    driver.SwitchTo().Window(driver.WindowHandles.Last());
    driver.Navigate().GoToUrl("http://www.google.com")
    

    Also you might need to switch back:

    driver.SwitchTo().Window(driver.WindowHandles.First());
    
    0 讨论(0)
  • 2020-12-28 21:29

    We can simulate Ctrl + Element Click

    Actions action = new Actions(_driver);
    action.KeyDown(Keys.Control).MoveToElement(body).Click().Perform();
    

    Reference:
    https://www.codeproject.com/Answers/1081051/Open-link-in-New-tab-using-Selenium-Csharp-for-chr#answer3

    0 讨论(0)
提交回复
热议问题