0
# Alert Handling
1
2
Interface for interacting with JavaScript alert, confirm, and prompt dialogs, providing methods to accept, dismiss, read text, and input data.
3
4
## Capabilities
5
6
### Alert Interface
7
8
Interface for interacting with JavaScript alert, confirm, and prompt dialogs.
9
10
```java { .api }
11
/**
12
* Alert interface for JavaScript dialog interaction
13
* Handles alert(), confirm(), and prompt() dialogs
14
*/
15
interface Alert {
16
/**
17
* Dismiss the alert (click Cancel/No/Dismiss button)
18
* Equivalent to pressing ESC key or clicking Cancel
19
*/
20
void dismiss();
21
22
/**
23
* Accept the alert (click OK/Yes/Accept button)
24
* Equivalent to pressing ENTER key or clicking OK
25
*/
26
void accept();
27
28
/**
29
* Get the text content of the alert dialog
30
* @return Alert message text
31
*/
32
String getText();
33
34
/**
35
* Send keys to prompt dialog input field
36
* Only applicable for prompt() dialogs with text input
37
* @param keysToSend - Text to enter in prompt input field
38
*/
39
void sendKeys(String keysToSend);
40
}
41
```
42
43
## Usage Examples
44
45
### Basic Alert Handling
46
47
```java
48
import org.openqa.selenium.WebDriver;
49
import org.openqa.selenium.Alert;
50
import org.openqa.selenium.By;
51
import org.openqa.selenium.chrome.ChromeDriver;
52
import org.openqa.selenium.support.ui.WebDriverWait;
53
import org.openqa.selenium.support.ui.ExpectedConditions;
54
import java.time.Duration;
55
56
WebDriver driver = new ChromeDriver();
57
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
58
59
try {
60
driver.get("https://example.com/alerts");
61
62
// Trigger alert and handle it
63
driver.findElement(By.id("alert-button")).click();
64
65
// Wait for alert to appear
66
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
67
68
// Get alert text
69
String alertText = alert.getText();
70
System.out.println("Alert message: " + alertText);
71
72
// Accept the alert
73
alert.accept();
74
75
} finally {
76
driver.quit();
77
}
78
```
79
80
### Different Types of Dialogs
81
82
```java
83
// Simple alert dialog
84
public void handleSimpleAlert() {
85
driver.findElement(By.id("simple-alert")).click();
86
87
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
88
System.out.println("Alert says: " + alert.getText());
89
alert.accept(); // Only option is to accept
90
}
91
92
// Confirmation dialog (OK/Cancel)
93
public boolean handleConfirmDialog(boolean acceptDialog) {
94
driver.findElement(By.id("confirm-button")).click();
95
96
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
97
String message = alert.getText();
98
System.out.println("Confirm dialog: " + message);
99
100
if (acceptDialog) {
101
alert.accept(); // Click OK
102
return true;
103
} else {
104
alert.dismiss(); // Click Cancel
105
return false;
106
}
107
}
108
109
// Prompt dialog (input field with OK/Cancel)
110
public String handlePromptDialog(String inputText) {
111
driver.findElement(By.id("prompt-button")).click();
112
113
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
114
String promptMessage = alert.getText();
115
System.out.println("Prompt message: " + promptMessage);
116
117
if (inputText != null) {
118
alert.sendKeys(inputText); // Enter text in prompt
119
alert.accept(); // Click OK
120
return inputText;
121
} else {
122
alert.dismiss(); // Click Cancel
123
return null;
124
}
125
}
126
```
127
128
### Advanced Alert Handling Patterns
129
130
```java
131
// Safe alert handling with error checking
132
public boolean handleAlertSafely(Duration timeout, boolean accept) {
133
try {
134
WebDriverWait alertWait = new WebDriverWait(driver, timeout);
135
Alert alert = alertWait.until(ExpectedConditions.alertIsPresent());
136
137
String alertText = alert.getText();
138
System.out.println("Alert detected: " + alertText);
139
140
if (accept) {
141
alert.accept();
142
} else {
143
alert.dismiss();
144
}
145
146
return true;
147
} catch (TimeoutException e) {
148
System.err.println("No alert appeared within " + timeout.getSeconds() + " seconds");
149
return false;
150
} catch (NoAlertPresentException e) {
151
System.err.println("Alert disappeared before it could be handled");
152
return false;
153
}
154
}
155
156
// Check if alert is present without waiting
157
public boolean isAlertPresent() {
158
try {
159
driver.switchTo().alert();
160
return true;
161
} catch (NoAlertPresentException e) {
162
return false;
163
}
164
}
165
166
// Handle alert with text validation
167
public boolean handleAlertWithValidation(String expectedText, boolean accept) {
168
try {
169
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
170
String actualText = alert.getText();
171
172
if (expectedText.equals(actualText)) {
173
System.out.println("Alert text matches expected: " + actualText);
174
if (accept) {
175
alert.accept();
176
} else {
177
alert.dismiss();
178
}
179
return true;
180
} else {
181
System.err.println("Alert text mismatch. Expected: '" + expectedText + "', Actual: '" + actualText + "'");
182
alert.dismiss(); // Dismiss unexpected alert
183
return false;
184
}
185
} catch (TimeoutException e) {
186
System.err.println("Expected alert did not appear");
187
return false;
188
}
189
}
190
```
191
192
### Alert Handling in Test Scenarios
193
194
```java
195
// Form validation alert handling
196
public void testFormValidation() {
197
// Fill form with invalid data
198
driver.findElement(By.id("email")).sendKeys("invalid-email");
199
driver.findElement(By.id("submit")).click();
200
201
// Handle validation alert
202
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
203
String validationMessage = alert.getText();
204
205
// Verify validation message
206
assertTrue("Validation message should contain 'email'",
207
validationMessage.toLowerCase().contains("email"));
208
209
alert.accept();
210
}
211
212
// Deletion confirmation
213
public void testDeleteConfirmation() {
214
// Click delete button
215
driver.findElement(By.className("delete-button")).click();
216
217
// Handle confirmation dialog
218
Alert confirmAlert = wait.until(ExpectedConditions.alertIsPresent());
219
String confirmText = confirmAlert.getText();
220
221
// Verify confirmation message
222
assertTrue("Confirmation should ask about deletion",
223
confirmText.toLowerCase().contains("delete"));
224
225
// Confirm deletion
226
confirmAlert.accept();
227
228
// Verify item was deleted (implementation specific)
229
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("deleted-item")));
230
}
231
232
// User input through prompt
233
public void testUserInputPrompt() {
234
String userInput = "Test User Name";
235
236
// Trigger prompt
237
driver.findElement(By.id("name-prompt")).click();
238
239
// Handle prompt dialog
240
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
241
System.out.println("Prompt: " + prompt.getText());
242
243
// Enter user input
244
prompt.sendKeys(userInput);
245
prompt.accept();
246
247
// Verify input was processed
248
WebElement result = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("user-name")));
249
assertEquals("User name should match input", userInput, result.getText());
250
}
251
```
252
253
### Multiple Alert Handling
254
255
```java
256
// Handle sequence of alerts
257
public void handleAlertSequence() {
258
driver.findElement(By.id("multiple-alerts")).click();
259
260
// First alert
261
Alert alert1 = wait.until(ExpectedConditions.alertIsPresent());
262
System.out.println("First alert: " + alert1.getText());
263
alert1.accept();
264
265
// Second alert
266
Alert alert2 = wait.until(ExpectedConditions.alertIsPresent());
267
System.out.println("Second alert: " + alert2.getText());
268
alert2.accept();
269
270
// Third alert (prompt)
271
Alert alert3 = wait.until(ExpectedConditions.alertIsPresent());
272
System.out.println("Third alert (prompt): " + alert3.getText());
273
alert3.sendKeys("Final input");
274
alert3.accept();
275
}
276
277
// Handle unexpected alerts during test
278
public void performActionWithAlertHandling(Runnable action) {
279
try {
280
action.run();
281
} catch (UnhandledAlertException e) {
282
System.out.println("Unexpected alert appeared: " + e.getAlertText());
283
284
// Handle the unexpected alert
285
Alert alert = driver.switchTo().alert();
286
alert.dismiss();
287
288
// Retry the action
289
action.run();
290
}
291
}
292
293
// Usage
294
performActionWithAlertHandling(() -> {
295
driver.findElement(By.id("risky-button")).click();
296
driver.findElement(By.id("next-step")).click();
297
});
298
```
299
300
### Alert Handling Utilities
301
302
```java
303
// Utility class for alert operations
304
public class AlertHelper {
305
private final WebDriver driver;
306
private final WebDriverWait wait;
307
308
public AlertHelper(WebDriver driver, Duration timeout) {
309
this.driver = driver;
310
this.wait = new WebDriverWait(driver, timeout);
311
}
312
313
public String getAlertText() {
314
try {
315
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
316
return alert.getText();
317
} catch (TimeoutException e) {
318
return null;
319
}
320
}
321
322
public boolean acceptAlert() {
323
try {
324
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
325
alert.accept();
326
return true;
327
} catch (TimeoutException e) {
328
return false;
329
}
330
}
331
332
public boolean dismissAlert() {
333
try {
334
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
335
alert.dismiss();
336
return true;
337
} catch (TimeoutException e) {
338
return false;
339
}
340
}
341
342
public boolean sendKeysToAlert(String text) {
343
try {
344
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
345
alert.sendKeys(text);
346
alert.accept();
347
return true;
348
} catch (TimeoutException e) {
349
return false;
350
}
351
}
352
353
public AlertAction waitForAlert() {
354
try {
355
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
356
return new AlertAction(alert);
357
} catch (TimeoutException e) {
358
return null;
359
}
360
}
361
362
// Fluent interface for alert actions
363
public static class AlertAction {
364
private final Alert alert;
365
366
public AlertAction(Alert alert) {
367
this.alert = alert;
368
}
369
370
public AlertAction validateText(String expectedText) {
371
String actualText = alert.getText();
372
if (!expectedText.equals(actualText)) {
373
throw new AssertionError("Alert text mismatch. Expected: '" + expectedText + "', Actual: '" + actualText + "'");
374
}
375
return this;
376
}
377
378
public AlertAction validateTextContains(String partialText) {
379
String actualText = alert.getText();
380
if (!actualText.contains(partialText)) {
381
throw new AssertionError("Alert text does not contain: '" + partialText + "'. Actual: '" + actualText + "'");
382
}
383
return this;
384
}
385
386
public AlertAction sendKeys(String text) {
387
alert.sendKeys(text);
388
return this;
389
}
390
391
public void accept() {
392
alert.accept();
393
}
394
395
public void dismiss() {
396
alert.dismiss();
397
}
398
399
public String getText() {
400
return alert.getText();
401
}
402
}
403
}
404
405
// Usage of utility class
406
AlertHelper alertHelper = new AlertHelper(driver, Duration.ofSeconds(5));
407
408
// Simple alert handling
409
String alertText = alertHelper.getAlertText();
410
boolean alertHandled = alertHelper.acceptAlert();
411
412
// Fluent alert handling
413
alertHelper.waitForAlert()
414
.validateTextContains("Are you sure")
415
.accept();
416
417
// Prompt handling
418
alertHelper.waitForAlert()
419
.validateText("Please enter your name:")
420
.sendKeys("John Doe");
421
```
422
423
### Alert Handling Best Practices
424
425
```java
426
// Comprehensive alert handling strategy
427
public class RobustAlertHandler {
428
private final WebDriver driver;
429
private final Duration defaultTimeout;
430
431
public RobustAlertHandler(WebDriver driver) {
432
this.driver = driver;
433
this.defaultTimeout = Duration.ofSeconds(10);
434
}
435
436
// Handle any type of alert with logging
437
public AlertResult handleAnyAlert(AlertStrategy strategy) {
438
try {
439
WebDriverWait wait = new WebDriverWait(driver, defaultTimeout);
440
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
441
442
String alertText = alert.getText();
443
System.out.println("Alert detected: " + alertText);
444
445
AlertResult result = new AlertResult(true, alertText);
446
447
switch (strategy) {
448
case ACCEPT:
449
alert.accept();
450
result.setAction("accepted");
451
break;
452
case DISMISS:
453
alert.dismiss();
454
result.setAction("dismissed");
455
break;
456
case ACCEPT_WITH_INPUT:
457
if (strategy.getInputText() != null) {
458
alert.sendKeys(strategy.getInputText());
459
}
460
alert.accept();
461
result.setAction("accepted with input: " + strategy.getInputText());
462
break;
463
}
464
465
return result;
466
467
} catch (TimeoutException e) {
468
System.out.println("No alert appeared within timeout");
469
return new AlertResult(false, null);
470
} catch (Exception e) {
471
System.err.println("Error handling alert: " + e.getMessage());
472
return new AlertResult(false, null);
473
}
474
}
475
476
enum AlertStrategy {
477
ACCEPT, DISMISS, ACCEPT_WITH_INPUT;
478
479
private String inputText;
480
481
public AlertStrategy withInput(String text) {
482
this.inputText = text;
483
return this;
484
}
485
486
public String getInputText() {
487
return inputText;
488
}
489
}
490
491
static class AlertResult {
492
private final boolean alertPresent;
493
private final String alertText;
494
private String action;
495
496
public AlertResult(boolean alertPresent, String alertText) {
497
this.alertPresent = alertPresent;
498
this.alertText = alertText;
499
}
500
501
// Getters and setters
502
public boolean isAlertPresent() { return alertPresent; }
503
public String getAlertText() { return alertText; }
504
public String getAction() { return action; }
505
public void setAction(String action) { this.action = action; }
506
}
507
}
508
509
// Usage
510
RobustAlertHandler alertHandler = new RobustAlertHandler(driver);
511
512
// Handle confirmation
513
AlertResult result = alertHandler.handleAnyAlert(AlertStrategy.ACCEPT);
514
if (result.isAlertPresent()) {
515
System.out.println("Alert was " + result.getAction() + ": " + result.getAlertText());
516
}
517
518
// Handle prompt with input
519
AlertResult promptResult = alertHandler.handleAnyAlert(
520
AlertStrategy.ACCEPT_WITH_INPUT.withInput("Test Input")
521
);
522
```