2

I have tried multiple actions but it is not working. It always close the first tab and then it open link in the same page.

// Driver is launched
package WebBrowserCommands;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class OpenBrowser 

{
    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver","/Users/ss108/Desktop/Util/SELENIUM SUPPORT/chromedriver");

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        // Driver is launched

        //We have two ways
        boolean Indriectway = true;
        //Boolean to understand both method

        if(!Indriectway){
            //Using String to take value.
            String URL = "https://www.google.com";
            driver.get(URL);

            String PageSourceFirst = driver.getPageSource();
            //We have took title in PageSourceFirst
            System.out.println(PageSourceFirst);

            //Get Title Command
            String TitleFrist = driver.getTitle();
            //We have took title in TitleFirst
            System.out.println("Tile of WebSite is " + TitleFrist);

            //Get Current URL
            String CurrentURLFirst = driver.getCurrentUrl();
            System.out.println("Current URL is " + CurrentURLFirst);

            Actions act=new Actions(driver);
            act.contextClick(driver.findElement(By.linkText("Gmail"))).perform();
            Thread.sleep(10000);
            act.contextClick(driver.findElement(By.linkText("Gmail"))).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();       
            // Try to open page using right click and action arrow down **but it is not working**

            driver.close();

        }else {
            //Using directly
            driver.get("https://www.facebook.com");
            String PageSourceSecond = driver.getPageSource();
            System.out.println(PageSourceSecond);

            //Get Title Command
            System.out.println("Tile of WebSite is " + driver.getTitle());
            //Get Current URL
            System.out.println("Current URL is " + driver.getCurrentUrl());
            driver.quit();

        }
    }
}

Second method 1- Same result getting

System.setProperty("webdriver.chrome.driver","/Users/ss108/Desktop/Util/SELENIUM SUPPORT/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.facebook.com")
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_META);
    robot.keyPress(KeyEvent.VK_T);
    robot.keyRelease(KeyEvent.VK_T);
    robot.keyRelease(KeyEvent.VK_META);  
    driver.get("https://www.google.com")

Third method

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);

however none of them work for what I am trying.

3 Answers 3

1

Each time main is run a new driver is created. The if-then-else is then used, but it is with a new driver each time. after each use driver.close(); closes the tab

Try creating a program structure that creates the driver once and then has methods that reuse that driver without closing it between tests.

See also https://sqa.stackexchange.com/a/1993/8992

0

This is how I'm doing it using the JS 'window.open' in my executeScript method in Protractor.

describe('Open a new window', ()=> {

  it('opening a new window', function() {      

     browser.executeScript('window.open()').then(function () {
         browser.getAllWindowHandles().then(function (handles) {
               var secondWindow = handles[1];
               browser.ignoreSynchronization = true;
               browser.switchTo().window(secondWindow).then(function () {
            // do whatever you want to do in new window
               });     
               var firstWindow = handles[0]
                browser.switchTo().window(firstWindow).then(function () {
                    console.log("Returning back");
              });
           });             
        });
     });
   });     
 });

You can try this using the JavaScript executor method for the corresponding language bindings. This works in Python too.

0

You can inject a link on the current page that opens in a new window/tab. Then switch to the new window handle. Here is the C# code I use:

    /// <summary>
    /// Injects a link on the current page and then clicks on that link (which opens a new tab).
    /// </summary>
    public static void OpenUrlInNewTab(IWebDriver driver, string url)
    {
        // Define the script
        string script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='" + url + "';a.innerHTML='.';d.body.appendChild(a);return a;";
        // Execute the JavaScript
        IWebElement element = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(script);
        // Click the new element
        element.Click();
        // Switch to the new tab
        driver.SwitchTo().Window(driver.WindowHandles.Last());
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.