0
# User Interactions
1
2
The Actions class provides advanced interaction capabilities including mouse actions, keyboard input, drag-and-drop operations, and action chaining for complex user workflows.
3
4
## Capabilities
5
6
### Actions Class
7
8
Advanced interaction builder for complex user actions including mouse, keyboard, and touch interactions.
9
10
```java { .api }
11
/**
12
* Actions class for building complex user interaction sequences
13
* Provides fluent interface for chaining multiple actions together
14
*/
15
class Actions {
16
/**
17
* Create Actions instance for specified WebDriver
18
* @param driver - WebDriver instance to perform actions on
19
*/
20
Actions(WebDriver driver);
21
22
/**
23
* Click at current mouse location
24
* @return Actions instance for chaining
25
*/
26
Actions click();
27
28
/**
29
* Click on specific element
30
* @param target - WebElement to click
31
* @return Actions instance for chaining
32
*/
33
Actions click(WebElement target);
34
35
/**
36
* Double-click at current mouse location
37
* @return Actions instance for chaining
38
*/
39
Actions doubleClick();
40
41
/**
42
* Double-click on specific element
43
* @param target - WebElement to double-click
44
* @return Actions instance for chaining
45
*/
46
Actions doubleClick(WebElement target);
47
48
/**
49
* Right-click (context click) at current mouse location
50
* @return Actions instance for chaining
51
*/
52
Actions contextClick();
53
54
/**
55
* Right-click (context click) on specific element
56
* @param target - WebElement to right-click
57
* @return Actions instance for chaining
58
*/
59
Actions contextClick(WebElement target);
60
61
/**
62
* Click and hold at current mouse location
63
* @return Actions instance for chaining
64
*/
65
Actions clickAndHold();
66
67
/**
68
* Click and hold on specific element
69
* @param target - WebElement to click and hold
70
* @return Actions instance for chaining
71
*/
72
Actions clickAndHold(WebElement target);
73
74
/**
75
* Release mouse button at current location
76
* @return Actions instance for chaining
77
*/
78
Actions release();
79
80
/**
81
* Release mouse button on specific element
82
* @param target - WebElement to release on
83
* @return Actions instance for chaining
84
*/
85
Actions release(WebElement target);
86
87
/**
88
* Drag from source element to target element
89
* @param source - Element to drag from
90
* @param target - Element to drag to
91
* @return Actions instance for chaining
92
*/
93
Actions dragAndDrop(WebElement source, WebElement target);
94
95
/**
96
* Drag element by specified offset
97
* @param source - Element to drag
98
* @param xOffset - Horizontal offset in pixels
99
* @param yOffset - Vertical offset in pixels
100
* @return Actions instance for chaining
101
*/
102
Actions dragAndDropBy(WebElement source, int xOffset, int yOffset);
103
104
/**
105
* Move mouse to specific element
106
* @param target - Element to move to
107
* @return Actions instance for chaining
108
*/
109
Actions moveToElement(WebElement target);
110
111
/**
112
* Move mouse to element with offset
113
* @param target - Element to move to
114
* @param xOffset - Horizontal offset from element center
115
* @param yOffset - Vertical offset from element center
116
* @return Actions instance for chaining
117
*/
118
Actions moveToElement(WebElement target, int xOffset, int yOffset);
119
120
/**
121
* Move mouse by specified offset from current position
122
* @param xOffset - Horizontal offset in pixels
123
* @param yOffset - Vertical offset in pixels
124
* @return Actions instance for chaining
125
*/
126
Actions moveByOffset(int xOffset, int yOffset);
127
128
/**
129
* Press and hold key
130
* @param key - Key to press down
131
* @return Actions instance for chaining
132
*/
133
Actions keyDown(Keys key);
134
135
/**
136
* Press and hold key on specific element
137
* @param target - Element to focus before key press
138
* @param key - Key to press down
139
* @return Actions instance for chaining
140
*/
141
Actions keyDown(WebElement target, Keys key);
142
143
/**
144
* Release key
145
* @param key - Key to release
146
* @return Actions instance for chaining
147
*/
148
Actions keyUp(Keys key);
149
150
/**
151
* Release key after focusing element
152
* @param target - Element to focus before key release
153
* @param key - Key to release
154
* @return Actions instance for chaining
155
*/
156
Actions keyUp(WebElement target, Keys key);
157
158
/**
159
* Send keys to currently focused element
160
* @param keys - Keys to send
161
* @return Actions instance for chaining
162
*/
163
Actions sendKeys(CharSequence... keys);
164
165
/**
166
* Send keys to specific element
167
* @param target - Element to send keys to
168
* @param keys - Keys to send
169
* @return Actions instance for chaining
170
*/
171
Actions sendKeys(WebElement target, CharSequence... keys);
172
173
/**
174
* Add pause to action sequence
175
* @param duration - Duration to pause
176
* @return Actions instance for chaining
177
*/
178
Actions pause(Duration duration);
179
180
/**
181
* Add pause using input source
182
* @param inputSource - Input source for pause
183
* @param duration - Duration to pause
184
* @return Actions instance for chaining
185
*/
186
Actions pause(InputSource inputSource, Duration duration);
187
188
/**
189
* Execute all queued actions
190
*/
191
void perform();
192
193
/**
194
* Build composite action without executing
195
* @return Action instance that can be performed later
196
*/
197
Action build();
198
}
199
```
200
201
## Mouse Interactions
202
203
### Basic Mouse Actions
204
205
```java
206
import org.openqa.selenium.WebDriver;
207
import org.openqa.selenium.WebElement;
208
import org.openqa.selenium.By;
209
import org.openqa.selenium.interactions.Actions;
210
import org.openqa.selenium.chrome.ChromeDriver;
211
212
WebDriver driver = new ChromeDriver();
213
Actions actions = new Actions(driver);
214
215
try {
216
driver.get("https://example.com");
217
218
// Single click
219
WebElement button = driver.findElement(By.id("clickMe"));
220
actions.click(button).perform();
221
222
// Double click
223
WebElement doubleClickTarget = driver.findElement(By.id("doubleClickMe"));
224
actions.doubleClick(doubleClickTarget).perform();
225
226
// Right click (context menu)
227
WebElement contextTarget = driver.findElement(By.id("rightClickMe"));
228
actions.contextClick(contextTarget).perform();
229
230
// Click at current mouse position
231
actions.click().perform();
232
233
} finally {
234
driver.quit();
235
}
236
```
237
238
### Mouse Movement and Hover
239
240
```java
241
// Move to element (hover)
242
WebElement menuItem = driver.findElement(By.id("menu"));
243
actions.moveToElement(menuItem).perform();
244
245
// Move to element with offset
246
WebElement canvas = driver.findElement(By.id("canvas"));
247
actions.moveToElement(canvas, 100, 50).perform(); // 100px right, 50px down from center
248
249
// Move by offset from current position
250
actions.moveByOffset(50, -25).perform(); // Move 50px right, 25px up
251
252
// Chain movements
253
actions.moveToElement(menuItem)
254
.pause(Duration.ofSeconds(1))
255
.moveToElement(driver.findElement(By.id("submenu")))
256
.click()
257
.perform();
258
```
259
260
### Drag and Drop Operations
261
262
```java
263
// Simple drag and drop
264
WebElement source = driver.findElement(By.id("draggable"));
265
WebElement target = driver.findElement(By.id("droppable"));
266
actions.dragAndDrop(source, target).perform();
267
268
// Drag and drop with offset
269
WebElement dragElement = driver.findElement(By.id("slider"));
270
actions.dragAndDropBy(dragElement, 100, 0).perform(); // Drag 100px to the right
271
272
// Manual drag and drop (more control)
273
actions.clickAndHold(source)
274
.moveToElement(target)
275
.release()
276
.perform();
277
278
// Complex drag with intermediate steps
279
actions.clickAndHold(source)
280
.moveByOffset(50, 0)
281
.pause(Duration.ofMilliseconds(500))
282
.moveByOffset(50, 0)
283
.moveToElement(target)
284
.release()
285
.perform();
286
```
287
288
## Keyboard Interactions
289
290
### Basic Keyboard Actions
291
292
```java
293
// Send keys to focused element
294
WebElement textField = driver.findElement(By.id("text"));
295
textField.click(); // Focus the element first
296
actions.sendKeys("Hello World").perform();
297
298
// Send keys to specific element
299
actions.sendKeys(textField, "Direct input").perform();
300
301
// Key combinations
302
actions.keyDown(Keys.CONTROL)
303
.sendKeys("a") // Ctrl+A (Select All)
304
.keyUp(Keys.CONTROL)
305
.perform();
306
307
// Multiple key combinations
308
actions.keyDown(Keys.CONTROL)
309
.keyDown(Keys.SHIFT)
310
.sendKeys("home") // Ctrl+Shift+Home
311
.keyUp(Keys.SHIFT)
312
.keyUp(Keys.CONTROL)
313
.perform();
314
```
315
316
### Advanced Keyboard Patterns
317
318
```java
319
// Copy and paste
320
WebElement sourceField = driver.findElement(By.id("source"));
321
WebElement targetField = driver.findElement(By.id("target"));
322
323
// Select all and copy
324
actions.click(sourceField)
325
.keyDown(Keys.CONTROL)
326
.sendKeys("a")
327
.sendKeys("c")
328
.keyUp(Keys.CONTROL)
329
.perform();
330
331
// Click target and paste
332
actions.click(targetField)
333
.keyDown(Keys.CONTROL)
334
.sendKeys("v")
335
.keyUp(Keys.CONTROL)
336
.perform();
337
338
// Tab navigation
339
actions.sendKeys(Keys.TAB) // Move to next field
340
.sendKeys("Tab input")
341
.sendKeys(Keys.SHIFT, Keys.TAB) // Move to previous field
342
.perform();
343
344
// Special keys
345
actions.sendKeys(Keys.ENTER).perform(); // Submit form
346
actions.sendKeys(Keys.ESCAPE).perform(); // Close dialog
347
actions.sendKeys(Keys.F5).perform(); // Refresh page
348
```
349
350
## Complex Action Sequences
351
352
### Multi-Step Interactions
353
354
```java
355
// Complex form interaction
356
WebElement form = driver.findElement(By.id("complexForm"));
357
WebElement field1 = form.findElement(By.name("field1"));
358
WebElement field2 = form.findElement(By.name("field2"));
359
WebElement dropdown = form.findElement(By.id("dropdown"));
360
WebElement submitBtn = form.findElement(By.id("submit"));
361
362
actions.click(field1)
363
.sendKeys("First value")
364
.sendKeys(Keys.TAB)
365
.sendKeys("Second value")
366
.click(dropdown)
367
.sendKeys(Keys.ARROW_DOWN)
368
.sendKeys(Keys.ARROW_DOWN)
369
.sendKeys(Keys.ENTER)
370
.click(submitBtn)
371
.perform();
372
```
373
374
### Canvas and Drawing Operations
375
376
```java
377
// Drawing on HTML5 canvas
378
WebElement canvas = driver.findElement(By.id("drawingCanvas"));
379
380
// Draw a square
381
actions.moveToElement(canvas, -50, -50) // Move to starting point
382
.clickAndHold()
383
.moveByOffset(100, 0) // Draw right side
384
.moveByOffset(0, 100) // Draw bottom side
385
.moveByOffset(-100, 0) // Draw left side
386
.moveByOffset(0, -100) // Draw top side
387
.release()
388
.perform();
389
390
// Draw with pauses for smooth animation
391
actions.moveToElement(canvas, 0, 0)
392
.clickAndHold()
393
.moveByOffset(10, 10).pause(Duration.ofMilliseconds(50))
394
.moveByOffset(10, 10).pause(Duration.ofMilliseconds(50))
395
.moveByOffset(10, 10).pause(Duration.ofMilliseconds(50))
396
.release()
397
.perform();
398
```
399
400
### Slider and Range Controls
401
402
```java
403
// Horizontal slider
404
WebElement slider = driver.findElement(By.id("priceRange"));
405
int sliderWidth = slider.getSize().getWidth();
406
407
// Move slider to 75% position
408
int targetOffset = (int) (sliderWidth * 0.75) - (sliderWidth / 2);
409
actions.moveToElement(slider)
410
.clickAndHold()
411
.moveByOffset(targetOffset, 0)
412
.release()
413
.perform();
414
415
// Vertical slider
416
WebElement verticalSlider = driver.findElement(By.id("volumeSlider"));
417
int sliderHeight = verticalSlider.getSize().getHeight();
418
419
// Move to 25% from bottom
420
int verticalOffset = (sliderHeight / 2) - (int) (sliderHeight * 0.25);
421
actions.moveToElement(verticalSlider)
422
.clickAndHold()
423
.moveByOffset(0, verticalOffset)
424
.release()
425
.perform();
426
```
427
428
## Action Chaining and Composition
429
430
### Building Reusable Action Sequences
431
432
```java
433
// Create reusable action for login
434
public Action createLoginAction(WebElement usernameField, WebElement passwordField,
435
WebElement loginButton, String username, String password) {
436
return new Actions(driver)
437
.click(usernameField)
438
.sendKeys(username)
439
.click(passwordField)
440
.sendKeys(password)
441
.click(loginButton)
442
.build();
443
}
444
445
// Use the reusable action
446
Action loginAction = createLoginAction(
447
driver.findElement(By.id("username")),
448
driver.findElement(By.id("password")),
449
driver.findElement(By.id("login")),
450
"testuser",
451
"testpass"
452
);
453
loginAction.perform();
454
455
// Chain multiple custom actions
456
Action fillFormAction = new Actions(driver)
457
.click(driver.findElement(By.id("firstName")))
458
.sendKeys("John")
459
.sendKeys(Keys.TAB)
460
.sendKeys("Doe")
461
.build();
462
463
Action submitFormAction = new Actions(driver)
464
.click(driver.findElement(By.id("submit")))
465
.build();
466
467
// Execute in sequence
468
fillFormAction.perform();
469
Thread.sleep(1000); // Wait between actions if needed
470
submitFormAction.perform();
471
```
472
473
### Error Handling in Action Sequences
474
475
```java
476
// Safe action execution with error handling
477
public void performActionSafely(Action action, String actionDescription) {
478
try {
479
action.perform();
480
System.out.println("Successfully performed: " + actionDescription);
481
} catch (Exception e) {
482
System.err.println("Failed to perform " + actionDescription + ": " + e.getMessage());
483
// Optionally take screenshot for debugging
484
takeScreenshot("failed_action_" + System.currentTimeMillis() + ".png");
485
}
486
}
487
488
// Retry pattern for flaky actions
489
public void performActionWithRetry(Actions actions, int maxRetries) {
490
for (int attempt = 1; attempt <= maxRetries; attempt++) {
491
try {
492
actions.perform();
493
return; // Success, exit method
494
} catch (Exception e) {
495
if (attempt == maxRetries) {
496
throw new RuntimeException("Action failed after " + maxRetries + " attempts", e);
497
}
498
// Wait before retry
499
try {
500
Thread.sleep(1000);
501
} catch (InterruptedException ie) {
502
Thread.currentThread().interrupt();
503
throw new RuntimeException("Interrupted during retry", ie);
504
}
505
}
506
}
507
}
508
```
509
510
### Performance Optimization
511
512
```java
513
// Batch actions for better performance
514
Actions batchActions = new Actions(driver);
515
516
// Add multiple actions to batch
517
WebElement form = driver.findElement(By.id("form"));
518
List<WebElement> fields = form.findElements(By.tagName("input"));
519
String[] values = {"Value1", "Value2", "Value3", "Value4"};
520
521
for (int i = 0; i < fields.size() && i < values.length; i++) {
522
batchActions.click(fields.get(i)).sendKeys(values[i]);
523
}
524
525
// Execute all actions at once
526
batchActions.perform();
527
528
// Use pauses strategically for timing-sensitive interactions
529
actions.moveToElement(dropdown)
530
.pause(Duration.ofMilliseconds(500)) // Wait for hover effect
531
.click(dropdown.findElement(By.className("option")))
532
.perform();
533
```