Skip to content
CodeKruPro

Automation tool (Selenium) · Java

Mouse, keyboard and JavaScript

Hover, drag and drop, key presses and running JavaScript.

Learn: Mouse, keyboard and JavaScript in Selenium Java7 minute read

Plain click() and sendKeys() cover most test steps. Some steps need more: a menu that opens only when the mouse is over it, drag and drop, a right-click menu, or holding Ctrl while clicking. Selenium Java handles these with the Actions class. For the few things WebDriver cannot do at all, there is JavascriptExecutor, which runs JavaScript (the programming language that web pages use) inside the page. Interviewers ask how both work and, just as often, when JavaScript is a bad idea.

The Actions class, step by step

Actions collects a chain of low-level input steps (move the mouse, press a button, press a key) and sends them to the browser together. Nothing happens until perform().

Actions actions = new Actions(driver);
actions.moveToElement(menu).perform();               // hover
actions.contextClick(row).perform();                 // right-click
actions.doubleClick(cell).perform();
actions.dragAndDrop(source, target).perform();
actions.clickAndHold(source).moveToElement(target).release().perform();
actions.keyDown(Keys.CONTROL).click(link).keyUp(Keys.CONTROL).perform();
actions.scrollToElement(footer).perform();

A typical hover task: move to the menu, wait for the submenu item to be visible (see Waits), then click it. A right-click only helps with menus the page draws itself; the browser's own context menu is outside the page and Selenium cannot click it.

build() versus perform()

This is a classic question. In Selenium 4, build() turns the queued steps into one Action object and empties the queue. perform() calls build() itself and then runs the result, so you never need build() before perform(). Keep build() for the rare case where you want to store an action and run it later.

Keyboard

For typing into a field, element.sendKeys(...) is enough, with Keys.ENTER, Keys.TAB or a chord such as Keys.chord(Keys.CONTROL, "a"). Use keyDown and keyUp in an Actions chain when a key must stay held during another step, such as Shift while typing or Ctrl while clicking. Always release what you press. On a Mac, use Keys.COMMAND where Windows and Linux use Ctrl.

When drag and drop does nothing

dragAndDrop sends pointer down, move and pointer up (press the mouse button, move, let go). Some pages use the HTML5 drag-and-drop events (signals the browser sends to the page while you drag), which do not always react to these simulated moves. Try the step-by-step chain with small moves and short pauses first. If the widget still ignores it, a JavaScript helper that fires the drag events is the usual workaround. Assert where the item ended up, not just that no exception was thrown.

JavascriptExecutor

Cast the driver (tell Java to treat it as a JavascriptExecutor) and pass elements as arguments. Inside the script they appear as arguments[0], arguments[1] and so on:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
String title = (String) js.executeScript("return document.title;");
Long rows = (Long) js.executeScript("return document.querySelectorAll('tr').length;");

Values come back only with return. Whole numbers arrive as Long (casting to Integer throws ClassCastException), decimals as Double, elements as WebElement, arrays as List and objects as Map. A script without return gives null.

Good reasons to use it: scrolling, reading a value the WebDriver API does not expose, or setting up page state quickly. A JavaScript click is a last resort for an overlay (a pop-up layer that sits on top of the button) you cannot remove.

Why a JavaScript click is risky

A JavaScript click calls the element's click handler (the page code that runs when the element is clicked) directly. It skips the checks a real user goes through: is the element visible, enabled, not covered? So the test can pass while real users cannot click the button, which is exactly the bug the test should catch. Setting value with JavaScript can also skip the input and change events the page listens to, so the app may ignore the new value.

How to answer in an interview

Name the use case, then the API: "For a hover menu I use Actions.moveToElement, then an explicit wait for the submenu." For JavaScript, say when you use it, show arguments[0] and return, and add the risk in one sentence. For infinite scroll (a list that loads more items as you reach the bottom), describe a loop: scroll, wait for the count to grow, stop when it does not, with a maximum number of rounds.

Common mistakes

  • Ending a chain without perform(), so nothing happens.
  • Pressing a key with keyDown and never releasing it.
  • Casting a JavaScript number to Integer.
  • Writing "document.title;" without return and getting null.
  • Replacing every failing click with a JavaScript click.

Recap

Actions handles hover, right-click, double-click, drag and drop and held keys, and runs on perform(). JavascriptExecutor runs scripts with arguments and returns values only with return. Prefer real user actions and use JavaScript with a clear reason.

16 questions0/16 solved

StatusQuestionDifficultyAsked in
Not startedbuild() versus perform() in the Actions classMedium
Not startedScroll to the bottom of the pageEasy-MediumAsked in: Accenture, Infosys, TCS
Not startedHover over an element with the actions APIMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedDrag a box onto a drop zoneMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedDouble-click a buttonEasy-MediumAsked in: Accenture, Capgemini, Infosys +2
Not startedRight-click (context click) a buttonEasy-MediumAsked in: Accenture, Capgemini, Infosys +2
Not startedClick and hold an element, then releaseMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedSelect all and replace text with the keyboardMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedHold Shift while typing with the actions APIMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedRead values with JavaScriptMediumAsked in: Infosys, TCS, Wipro
Not startedScroll an element into view with JavaScriptMediumAsked in: Accenture, Infosys, TCS
Not startedClick a button through JavaScriptMediumAsked in: Infosys, TCS, Wipro
Not startedChange the page with JavaScriptMediumAsked in: Infosys, TCS, Wipro
Pro+When and how do you use JavascriptExecutor?MediumAsked in: Accenture, Infosys, TCS +1
Pro+What type does executeScript return for a number?MediumAsked in: Infosys, TCS, Wipro
Pro+Ctrl+click with the Actions class (Java)MediumAsked in: Accenture, Capgemini, Infosys +2
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan