Using JavascriptExecutor to sendKeys plus click on a web element

I am trying to open a link in a new tab and then go to that tab in Firefox browser using selenium in Java. I understand that I need to use the submit key combination for this.

To open the link in the same window, I used something like this:

WebElement we = driver.findElement(By.xpath("//*[@id='btn']"));

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", we);

      

The above was great for me.

Now I am also trying to sendKeys as below which doesnt work:

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("keyDown(Keys.CONTROL)
                        .keyDown(Keys.SHIFT)
                        .click(arguments[0])
                        .keyUp(Keys.CONTROL)
                        .keyUp(Keys.SHIFT);", we);

      

Any advice? I cannot figure out the correct sendKeys syntax for the JavascriptExecutor. I've seen some similar solutions using Actions, but that didn't work for me either.

+3


source to share


1 answer


try entering the code to open any link on the page to a new tab and go to that tab. Perform operations there and return to the first tab for further execution.



WebDriver driver = new FirefoxDriver();
        driver.get("http://stackoverflow.com/");
        WebElement e = driver.findElement(By.xpath(".//*[@id='nav-questions']"));       
        Actions action = new Actions(driver); 
        action.keyDown(Keys.CONTROL).build().perform(); //press control key
        e.click();
        Thread.sleep(10000); // wait till your page loads in new tab
        action.keyUp(Keys.CONTROL).build().perform(); //release control key
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //move to new tab
        driver.navigate().refresh(); // refresh page
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click(); //perform any action in new tab. I am just clicking logo
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //switch to first tab
        driver.navigate().refresh(); 
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click();// refresh first tab & continue with your further work.I am just clicking logo

      

+1


source







All Articles