简体   繁体   English

如何使用“executeScript”在Selenium中通过JavaScript发送“Enter Key”

[英]How To Send "Enter Key" via JavaScript in Selenium using "executeScript"

I'm working on automating a flow using IE 11 with Selenium and Java, on this web page I need to put a value in Text Box and then press Enter.我正在使用带有 Selenium 和 Java 的 IE 11 自动化流程,在此网页上,我需要在文本框中输入一个值,然后按 Enter。 I'm able to put the values using below code -我可以使用以下代码放置值 -

// Here Box is a webElement

JavascriptExecutor js = (JavascriptExecutor)iedriver; 
js.executeScript("arguments[0].value='1500';",box);

which is working as expected, but when I try to use box.sendKeys(Keys.Enter) it doesn't work.它按预期工作,但是当我尝试使用box.sendKeys(Keys.Enter)它不起作用。 So what is the way I could achieve "pressing Enter key via JavaScript".那么我可以通过什么方式实现“通过 JavaScript 按下 Enter 键”。

I have tried below code as well, but this is also not working.我也试过下面的代码,但这也不起作用。

Actions actions = new Actions(iedriver);
actions.moveToElement(box).sendKeys(Keys.RETURN).build().perform();

There is no error message, code executes but on web page Enter Key is not pressed.没有错误消息,代码执行但在网页上没有按下 Enter 键。

If you want to do it via JavaScript you can consider using KeyboardEvent.initKeyBoardEvent() function like:如果你想通过 JavaScript 来做,你可以考虑使用KeyboardEvent.initKeyBoardEvent()函数,如:

document.body.dispatchEvent(document.createEvent('KeyboardEvent').initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0));

However I wouldn't recommend looking into that direction, instead you could try calling submit() function on the WebElement as simple as:但是,我不建议研究这个方向,相反,您可以尝试在WebElement上调用submit()函数,就像这样简单:

box.submit();

Also going forward consider refactoring your test suite to make use of Page Object Model Design Pattern which allows you to abstract DOM elements representation from the test logic.还要考虑重构您的测试套件以利用页面对象模型设计模式,该模式允许您从测试逻辑中抽象出DOM元素表示。

Have you tried using the Java Robot to press the enter key?您是否尝试过使用 Java Robot 按 Enter 键?

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Don't forget the release key otherwise system will act as if the enter key is kept pressed down不要忘记释放键,否则系统会表现得好像一直按下回车键一样

reference: https://docs.oracle.com/javase/8/docs/api/java/awt/Robot.html参考: https : //docs.oracle.com/javase/8/docs/api/java/awt/Robot.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM