简体   繁体   中英

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. 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. So what is the way I could achieve "pressing Enter key via JavaScript".

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.

If you want to do it via JavaScript you can consider using KeyboardEvent.initKeyBoardEvent() function like:

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:

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.

Have you tried using the Java Robot to press the enter key?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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