Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a link in new tab (chrome) using Selenium WebDriver?

Tags:

System.setProperty("webdriver.chrome.driver", "D:\\softwares\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://mail.google.com/");
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);

New tab is opening but URL link is not opening.

like image 716
nlogn Avatar asked Jan 16 '16 16:01

nlogn


People also ask

How do I switch to a new window in Selenium?

Use the SwitchTo command to switch to the desired window and also pass the URL of the web page.

What is the use of JavascriptExecutor in Selenium WebDriver?

What is JavascriptExecutor in Selenium? In simple words, JavascriptExecutor is an interface that is used to execute JavaScript with Selenium. To simplify the usage of JavascriptExecutor in Selenium, think of it as a medium that enables the WebDriver to interact with HTML elements within the browser.


2 Answers

this below code works for me in Selenium 3 and chrome version 58.

    WebDriver driver = new ChromeDriver();
    driver.get("http://yahoo.com");  
    ((JavascriptExecutor)driver).executeScript("window.open()");
    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://google.com");
like image 165
nur Avatar answered Oct 22 '22 01:10

nur


I checked with below code and it works fine for me. I found answer from here.

    driver = new ChromeDriver();
    driver.manage().window().maximize();
            
    String baseUrl = "http://www.google.co.uk/";
    driver.get(baseUrl);
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

    ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1)); //switches to new tab
    driver.get("https://www.facebook.com");
    
    driver.switchTo().window(tabs.get(0)); // switch back to main screen        
    driver.get("https://www.news.google.com");
like image 24
Abdul Hameed Avatar answered Oct 22 '22 01:10

Abdul Hameed