Search code examples
c#seleniumselenium-webdriverautomation

How to open Previously copy link in the new tab in selenium C#?


Suppose you copy a link by clicking on the button and you want to open that copied link in a new tab, then how to perform this operation in selenium C#.

driver.FindElement(By.Id("button")).click(); -----from this operation we just copy the link.

Question: Now How to open this copy link in new tab ?


Solution

  • After getting the URL link with code like this:

    var url = driver.FindElement(By.Id("button")).Text;
    

    You can open a new tab and switch to it with

    ((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
    driver.SwitchTo().Window(driver.WindowHandles.Last());
    

    And then open the previously saved url there with driver with

    driver.Url = url;
    

    So that the entire code could be something like this:

    var url = driver.FindElement(By.Id("button")).Text;
    ((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
    driver.SwitchTo().Window(driver.WindowHandles.Last());
    driver.Url = url;
    

    In case you are getting the URL by clicking on that element as you mentioned driver.FindElement(By.Id("button")).click(); so that the URL is copied into the clipboard, you can use code like this:

    using System.Windows.Forms;
    driver.FindElement(By.Id("button")).click();
    string url = Clipboard.GetText()
    ((IJavaScriptExecutor)_chromeDriver).ExecuteScript("window.open('" + url +"');");