Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavascriptExecutor to sendKeys plus click on web element

I'm trying to open a link in a new tab, then switch to that tab, in a Firefox browser, using selenium in Java. It's my understanding that in order to do this, I need to use a send keys combination.

In order to open the link in the same window, I've been using something like this:

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

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

The above was working fine for me.

Now I'm trying to also sendKeys, as in below, which is not working:

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 can't figure out the correct syntax to sendKeys to JavascriptExecutor. I've seen some similar solutions using Actions, but this hasn't worked for me either.

like image 970
ch-pub Avatar asked Jul 26 '15 02:07

ch-pub


1 Answers

try below code to open any link on page to new tab & switch to that tab. Perform operations there & go back to 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
like image 139
Deepak Avatar answered Oct 02 '22 17:10

Deepak