[英]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. 我正在尝试在新选项卡中打开一个链接,然后在Firefox浏览器中使用Java中的selenium切换到该选项卡。 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. 我无法弄清楚sendKeys到JavascriptExecutor的正确语法。 I've seen some similar solutions using Actions, but this hasn't worked for me either. 我已经看过一些使用Actions的类似解决方案,但这对我来说也没有用。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.