<div class="selenium-notes">
<h1>JavaScript Alerts in Selenium</h1>
<p>JavaScript Alerts are browser-level dialog boxes generated by JavaScript that require a specific user action before the browser can continue interacting with the web page. In Selenium automation, JavaScript alerts cannot be handled like normal HTML WebElements because they are outside the regular DOM. Selenium provides the <strong>Alert</strong> interface through which testers can switch to, read, accept, dismiss, and enter text into JavaScript alert dialogs.</p>
<p>Handling alerts is an important part of Selenium WebDriver automation because real-world web applications may display confirmation messages, warnings, authentication prompts, delete confirmations, session notifications, and other JavaScript-based dialogs during test execution.</p>
<p>For structured Selenium learning and practical automation training, visit <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Selenium Course Demo</a>.</p>
<hr>
<h2>1. What is a JavaScript Alert?</h2>
<p>A JavaScript alert is a browser dialog displayed by JavaScript to communicate information to the user or request an action. These dialogs temporarily interrupt normal interaction with the web page until the user responds.</p>
<p>For example:</p>
<pre><code>alert("Record saved successfully");</code></pre>
<p>When this JavaScript executes, the browser displays a dialog containing the message and an <strong>OK</strong> button.</p>
<hr>
<h2>2. Why JavaScript Alerts are Important in Selenium</h2>
<p>Automated test scripts frequently encounter JavaScript dialogs while testing web applications. If Selenium encounters an unexpected alert and the script does not handle it correctly, subsequent browser interactions may fail.</p>
<ul>
<li>Alerts can block interaction with the page.</li>
<li>The alert must usually be handled before interacting with the underlying page.</li>
<li>Alert text can be verified during testing.</li>
<li>Confirmation dialogs can be accepted or dismissed.</li>
<li>Prompt dialogs can require text input.</li>
<li>Unexpected alerts can cause test execution failures.</li>
</ul>
<hr>
<h2>3. How JavaScript Alerts Work</h2>
<p>A JavaScript alert is created by JavaScript running inside the web application.</p>
<p>Basic flow:</p>
<pre><code>Web Page
↓
JavaScript Executes
↓
Browser Dialog Appears
↓
Selenium Detects Alert
↓
driver.switchTo().alert()
↓
Accept / Dismiss / Get Text / Send Keys
↓
Browser Continues</code></pre>
<hr>
<h2>4. Types of JavaScript Dialogs</h2>
<p>The three primary JavaScript dialog types commonly encountered in Selenium are:</p>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Dialog Type</th><th>JavaScript Method</th><th>Typical Buttons</th><th>Purpose</th></tr>
<tr><td>Alert</td><td>alert()</td><td>OK</td><td>Displays information or warning</td></tr>
<tr><td>Confirmation</td><td>confirm()</td><td>OK / Cancel</td><td>Requests user confirmation</td></tr>
<tr><td>Prompt</td><td>prompt()</td><td>OK / Cancel</td><td>Requests text input</td></tr>
</table>
<hr>
<h2>5. JavaScript alert()</h2>
<p>The <code>alert()</code> method displays a simple message and normally provides an <strong>OK</strong> button.</p>
<pre><code><script>
alert("Welcome to the application");
</script></code></pre>
<p>In Selenium, the alert can be accepted using:</p>
<pre><code>Alert alert = driver.switchTo().alert();
alert.accept();</code></pre>
<hr>
<h2>6. JavaScript confirm()</h2>
<p>The <code>confirm()</code> method displays a confirmation dialog. It normally provides <strong>OK</strong> and <strong>Cancel</strong> buttons.</p>
<pre><code><script>
confirm("Are you sure you want to delete this record?");
</script></code></pre>
<p>Clicking OK is equivalent to accepting the alert:</p>
<pre><code>Alert alert = driver.switchTo().alert();
alert.accept();</code></pre>
<p>Clicking Cancel is equivalent to dismissing it:</p>
<pre><code>Alert alert = driver.switchTo().alert();
alert.dismiss();</code></pre>
<hr>
<h2>7. JavaScript prompt()</h2>
<p>The <code>prompt()</code> method displays a dialog that allows the user to enter text.</p>
<pre><code><script>
prompt("Enter your username");
</script></code></pre>
<p>Selenium can enter text into a prompt using <code>sendKeys()</code>.</p>
<pre><code>Alert alert = driver.switchTo().alert();
alert.sendKeys("Manish");
alert.accept();</code></pre>
<hr>
<h2>8. Selenium Alert Interface</h2>
<p>Selenium provides the <code>Alert</code> interface for interacting with JavaScript dialogs.</p>
<p>The most commonly used methods are:</p>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Method</th><th>Purpose</th></tr>
<tr><td><code>accept()</code></td><td>Clicks the OK button</td></tr>
<tr><td><code>dismiss()</code></td><td>Clicks the Cancel button</td></tr>
<tr><td><code>getText()</code></td><td>Retrieves alert message text</td></tr>
<tr><td><code>sendKeys()</code></td><td>Enters text into a prompt</td></tr>
</table>
<hr>
<h2>9. Switching to an Alert</h2>
<p>Before interacting with a JavaScript alert, Selenium must switch the driver's focus to the alert.</p>
<pre><code>Alert alert = driver.switchTo().alert();</code></pre>
<p>Alternatively, the statement can be written directly:</p>
<pre><code>driver.switchTo().alert().accept();</code></pre>
<hr>
<h2>10. Accepting an Alert</h2>
<p>The <code>accept()</code> method clicks the OK button of the JavaScript dialog.</p>
<pre><code>driver.switchTo().alert().accept();</code></pre>
<p>Typical use cases include:</p>
<ul>
<li>Closing an information alert</li>
<li>Confirming deletion</li>
<li>Confirming submission</li>
<li>Accepting a warning</li>
<li>Confirming an action</li>
</ul>
<hr>
<h2>11. Dismissing an Alert</h2>
<p>The <code>dismiss()</code> method clicks the Cancel button when the dialog provides one.</p>
<pre><code>driver.switchTo().alert().dismiss();</code></pre>
<p>This is commonly used when testing negative or cancellation scenarios.</p>
<hr>
<h2>12. Getting Alert Text</h2>
<p>The <code>getText()</code> method retrieves the text displayed inside the alert.</p>
<pre><code>Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println(message);</code></pre>
<p>This is useful when the expected alert message is part of the test requirement.</p>
<hr>
<h2>13. Verifying Alert Text</h2>
<p>Alert text can be verified using Java assertions.</p>
<pre><code>Alert alert = driver.switchTo().alert();
String actualMessage = alert.getText();
String expectedMessage = "Record deleted successfully";
Assert.assertEquals(actualMessage, expectedMessage);
alert.accept();</code></pre>
<hr>
<h2>14. Sending Text to a Prompt</h2>
<p>A prompt allows the user to enter information. Selenium uses the <code>sendKeys()</code> method to provide that input.</p>
<pre><code>Alert alert = driver.switchTo().alert();
alert.sendKeys("Test User");
alert.accept();</code></pre>
<hr>
<h2>15. Complete Alert Handling Example</h2>
<pre><code>import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
driver.get("https://example.com");
driver.findElement(By.id("alertButton")).click();
Alert alert = driver.switchTo().alert();
System.out.println("Alert Message: " + alert.getText());
alert.accept();
driver.quit();
}
}</code></pre>
<hr>
<h2>16. Alert Handling Methods Summary</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Operation</th><th>Selenium Code</th></tr>
<tr><td>Switch to alert</td><td><code>driver.switchTo().alert()</code></td></tr>
<tr><td>Accept</td><td><code>alert.accept()</code></td></tr>
<tr><td>Dismiss</td><td><code>alert.dismiss()</code></td></tr>
<tr><td>Read text</td><td><code>alert.getText()</code></td></tr>
<tr><td>Enter prompt text</td><td><code>alert.sendKeys("text")</code></td></tr>
</table>
<hr>
<h2>17. Alert vs HTML Modal</h2>
<p>One of the most important concepts in Selenium is understanding the difference between a JavaScript alert and an HTML modal dialog.</p>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>JavaScript Alert</th><th>HTML Modal</th></tr>
<tr><td>Browser-managed dialog</td><td>Part of the web page DOM</td></tr>
<tr><td>Handled using Alert interface</td><td>Handled using WebElement locators</td></tr>
<tr><td>Use <code>switchTo().alert()</code></td><td>Use <code>findElement()</code></td></tr>
<tr><td>Not normally inspected as a normal DOM element</td><td>Can usually be inspected in DevTools</td></tr>
<tr><td>Can block page interaction</td><td>Usually behaves like page content</td></tr>
</table>
<hr>
<h2>18. JavaScript Alert vs Browser Popup</h2>
<p>Not every popup displayed by a website is a JavaScript alert.</p>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Popup Type</th><th>Typical Selenium Handling</th></tr>
<tr><td>JavaScript Alert</td><td><code>driver.switchTo().alert()</code></td></tr>
<tr><td>HTML Modal</td><td>WebElement locators</td></tr>
<tr><td>New Browser Window</td><td>Window handles</td></tr>
<tr><td>New Browser Tab</td><td>Window handles</td></tr>
<tr><td>Authentication Dialog</td><td>Depends on browser/application implementation</td></tr>
</table>
<hr>
<h2>19. Why switchTo().alert() is Required</h2>
<p>Selenium normally interacts with elements in the current browsing context. A JavaScript alert is a separate browser-level dialog. Therefore, Selenium must change its current interaction target to the alert.</p>
<pre><code>driver.switchTo().alert();</code></pre>
<p>After switching, Selenium can perform alert-specific operations.</p>
<hr>
<h2>20. What Happens if an Alert is Not Handled?</h2>
<p>If an alert is open and the test tries to interact with the underlying page, Selenium may fail because the alert is blocking normal browser interaction.</p>
<p>For example:</p>
<pre><code>driver.findElement(By.id("submit")).click();
driver.switchTo().alert().accept();</code></pre>
<p>The sequence is incorrect when the alert appears before the submit interaction can continue. The alert should be handled at the point where it appears.</p>
<hr>
<h2>21. Correct Alert Handling Flow</h2>
<pre><code>Perform Action
↓
Alert Appears
↓
Switch to Alert
↓
Read Alert Text if Required
↓
Accept or Dismiss
↓
Continue Test</code></pre>
<hr>
<h2>22. Alert Handling with Explicit Wait</h2>
<p>Alerts may not appear immediately after an action. In such cases, an explicit wait can wait for the alert to become available.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.findElement(By.id("deleteButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println(alert.getText());
alert.accept();</code></pre>
<p><code>alertIsPresent()</code> is useful when the alert appears asynchronously.</p>
<hr>
<h2>23. Why Explicit Wait is Useful for Alerts</h2>
<ul>
<li>The alert may appear after a small delay.</li>
<li>The page may perform an asynchronous operation before showing the dialog.</li>
<li>A fixed sleep may wait too long or too little.</li>
<li>An explicit wait can stop as soon as the alert is available.</li>
<li>It makes synchronization more targeted.</li>
</ul>
<hr>
<h2>24. Thread.sleep() with Alerts</h2>
<p>A fixed delay can technically be used, but it is generally less desirable for reliable automation.</p>
<pre><code>Thread.sleep(3000);
driver.switchTo().alert().accept();</code></pre>
<p>The problem is that the alert may appear before three seconds or after three seconds. An explicit wait is usually more appropriate for dynamic timing.</p>
<hr>
<h2>25. AlertNotPresent Scenario</h2>
<p>If Selenium tries to switch to an alert when no alert is currently present, an exception can occur.</p>
<pre><code>driver.switchTo().alert();</code></pre>
<p>When no alert exists, Selenium may throw <code>NoAlertPresentException</code>.</p>
<hr>
<h2>26. Handling NoAlertPresentException</h2>
<p>The exception can be handled when the alert is optional or when the test needs controlled recovery.</p>
<pre><code>try {
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
} catch (NoAlertPresentException e) {
System.out.println("No alert was displayed.");
}</code></pre>
<p>However, exceptions should not simply be swallowed. If an alert was required by the test, the test should normally fail or report the missing alert rather than silently continuing.</p>
<hr>
<h2>27. Optional Alert Handling</h2>
<p>Sometimes an application displays an alert only under certain conditions. In such situations, the test can wait briefly for an alert and then continue if it does not appear.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println(alert.getText());
alert.accept();
} catch (TimeoutException e) {
System.out.println("Optional alert did not appear.");
}</code></pre>
<hr>
<h2>28. Alert Text Validation</h2>
<p>Validation should compare the actual message with the expected business requirement.</p>
<pre><code>Alert alert = driver.switchTo().alert();
String actual = alert.getText();
Assert.assertEquals(
actual,
"Are you sure you want to delete this record?"
);
alert.dismiss();</code></pre>
<hr>
<h2>29. Testing Confirmation Dialogs</h2>
<p>Confirmation dialogs are commonly used for destructive operations such as deleting a record.</p>
<pre><code>driver.findElement(By.id("deleteButton")).click();
Alert alert = driver.switchTo().alert();
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete this record?"
);
alert.accept();</code></pre>
<hr>
<h2>30. Testing Cancel Operation</h2>
<p>Negative testing should also verify what happens when the user chooses Cancel.</p>
<pre><code>driver.findElement(By.id("deleteButton")).click();
Alert alert = driver.switchTo().alert();
alert.dismiss();</code></pre>
<p>The test can then verify that the record was not deleted.</p>
<hr>
<h2>31. Testing Prompt Dialogs</h2>
<p>A prompt should be tested by entering valid, invalid, empty, boundary, and special-character values when those scenarios are part of the application's requirements.</p>
<pre><code>driver.findElement(By.id("promptButton")).click();
Alert alert = driver.switchTo().alert();
alert.sendKeys("Automation Tester");
alert.accept();</code></pre>
<hr>
<h2>32. Prompt Testing with Verification</h2>
<pre><code>driver.findElement(By.id("promptButton")).click();
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println("Prompt Message: " + message);
alert.sendKeys("Selenium User");
alert.accept();
String result = driver.findElement(By.id("result")).getText();
Assert.assertEquals(result, "Selenium User");</code></pre>
<hr>
<h2>33. Handling an Alert After Clicking a Button</h2>
<p>A common Selenium scenario is clicking a button that triggers a JavaScript alert.</p>
<pre><code>driver.findElement(By.id("showAlert")).click();
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();</code></pre>
<hr>
<h2>34. Handling an Alert After Form Submission</h2>
<pre><code>driver.findElement(By.id("username")).sendKeys("testuser");
driver.findElement(By.id("password")).sendKeys("password123");
driver.findElement(By.id("login")).click();
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println("Alert: " + message);
alert.accept();</code></pre>
<hr>
<h2>35. Alert Handling with TestNG</h2>
<pre><code>import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void verifyAlert() {
driver.findElement(By.id("alertButton")).click();
Alert alert = driver.switchTo().alert();
String actualMessage = alert.getText();
Assert.assertEquals(
actualMessage,
"Operation completed successfully"
);
alert.accept();
}</code></pre>
<hr>
<h2>36. Alert Handling in Page Object Model</h2>
<p>Alert-related operations can be encapsulated inside page classes when the alert belongs logically to a page action.</p>
<pre><code>public void deleteRecord() {
deleteButton.click();
}
public String getAlertMessage() {
return driver.switchTo().alert().getText();
}
public void acceptAlert() {
driver.switchTo().alert().accept();
}
public void dismissAlert() {
driver.switchTo().alert().dismiss();
}</code></pre>
<hr>
<h2>37. Creating an Alert Utility</h2>
<p>A reusable alert utility can reduce duplicate code across automation tests.</p>
<pre><code>public class AlertHelper {
private WebDriver driver;
public AlertHelper(WebDriver driver) {
this.driver = driver;
}
public void acceptAlert() {
driver.switchTo().alert().accept();
}
public void dismissAlert() {
driver.switchTo().alert().dismiss();
}
public String getAlertText() {
return driver.switchTo().alert().getText();
}
public void enterText(String text) {
driver.switchTo().alert().sendKeys(text);
}
}</code></pre>
<hr>
<h2>38. Alert Utility Usage</h2>
<pre><code>AlertHelper alertHelper = new AlertHelper(driver);
driver.findElement(By.id("deleteButton")).click();
String message = alertHelper.getAlertText();
System.out.println(message);
alertHelper.acceptAlert();</code></pre>
<hr>
<h2>39. Alert Handling Best Practices</h2>
<ul>
<li>Handle alerts immediately when they appear.</li>
<li>Use explicit waits when alert appearance is asynchronous.</li>
<li>Validate alert text when it is part of the requirement.</li>
<li>Use <code>accept()</code> for OK.</li>
<li>Use <code>dismiss()</code> for Cancel.</li>
<li>Use <code>sendKeys()</code> for prompt input.</li>
<li>Do not treat HTML modals as JavaScript alerts.</li>
<li>Avoid unnecessary <code>Thread.sleep()</code>.</li>
<li>Use reusable alert helper methods in larger frameworks.</li>
<li>Report unexpected alerts clearly.</li>
</ul>
<hr>
<h2>40. Common Mistake: Treating an Alert as a WebElement</h2>
<p>Incorrect approach:</p>
<pre><code>WebElement alert = driver.findElement(By.id("alert"));</code></pre>
<p>A native JavaScript alert is not normally handled as a DOM WebElement. The correct approach is:</p>
<pre><code>Alert alert = driver.switchTo().alert();</code></pre>
<hr>
<h2>41. Common Mistake: Calling accept() Directly on WebDriver</h2>
<p>The <code>WebDriver</code> object does not provide the <code>accept()</code> method directly.</p>
<p>Correct:</p>
<pre><code>driver.switchTo().alert().accept();</code></pre>
<hr>
<h2>42. Common Mistake: Using getText() on WebDriver</h2>
<p>The alert text should be retrieved from the <code>Alert</code> object.</p>
<pre><code>Alert alert = driver.switchTo().alert();
String message = alert.getText();</code></pre>
<hr>
<h2>43. Common Mistake: Using sendKeys() on the Page</h2>
<p>For a JavaScript prompt, the text should be sent to the alert object.</p>
<pre><code>Alert alert = driver.switchTo().alert();
alert.sendKeys("Test Data");
alert.accept();</code></pre>
<hr>
<h2>44. Common Mistake: Using Dismiss on a Simple Alert</h2>
<p>A simple <code>alert()</code> normally has only an OK button. The normal operation is to accept it.</p>
<pre><code>driver.switchTo().alert().accept();</code></pre>
<hr>
<h2>45. Common Mistake: Not Waiting for Dynamic Alerts</h2>
<p>If the alert is created asynchronously, immediately calling <code>switchTo().alert()</code> may execute before the alert exists.</p>
<p>Use:</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.accept();</code></pre>
<hr>
<h2>46. Alert Handling and Synchronization</h2>
<p>Alert handling and synchronization are closely related. A test must synchronize with the point at which the browser dialog becomes available.</p>
<pre><code>Click Button
↓
Application Processing
↓
JavaScript Executes
↓
Alert Appears
↓
Wait for Alert
↓
Switch to Alert
↓
Validate / Accept / Dismiss
↓
Continue Test</code></pre>
<hr>
<h2>47. Alert Handling in Dynamic Web Applications</h2>
<p>Modern applications may trigger JavaScript dialogs after AJAX requests, asynchronous operations, validation checks, or API responses. Therefore, alert timing should not always be assumed to be immediate.</p>
<pre><code>driver.findElement(By.id("processButton")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
System.out.println(message);
alert.accept();</code></pre>
<hr>
<h2>48. Alert and Page State</h2>
<p>After accepting or dismissing an alert, Selenium can normally continue interacting with the page.</p>
<pre><code>Alert alert = driver.switchTo().alert();
alert.accept();
driver.findElement(By.id("nextButton")).click();</code></pre>
<hr>
<h2>49. Handling Multiple Alerts</h2>
<p>If multiple alerts appear sequentially, each alert must be handled before continuing to the next application action.</p>
<pre><code>Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
Alert secondAlert = driver.switchTo().alert();
System.out.println(secondAlert.getText());
secondAlert.accept();</code></pre>
<p>In dynamic applications, explicit waits can be added before each alert when necessary.</p>
<hr>
<h2>50. Reusable Method for Accepting Alerts</h2>
<pre><code>public void acceptAlert(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
}</code></pre>
<hr>
<h2>51. Reusable Method for Reading Alert Text</h2>
<pre><code>public String getAlertText(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
return alert.getText();
}</code></pre>
<hr>
<h2>52. Reusable Method for Prompt Input</h2>
<pre><code>public void enterAlertText(WebDriver driver, String text) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.sendKeys(text);
alert.accept();
}</code></pre>
<hr>
<h2>53. Alert Handling in a Login Test</h2>
<p>Some applications may display an alert when invalid login credentials are submitted.</p>
<pre><code>driver.findElement(By.id("username")).sendKeys("wrongUser");
driver.findElement(By.id("password")).sendKeys("wrongPassword");
driver.findElement(By.id("loginButton")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Invalid username or password");
alert.accept();</code></pre>
<hr>
<h2>54. Alert Handling in a Delete Test</h2>
<pre><code>driver.findElement(By.id("deleteButton")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete?"
);
alert.accept();
Assert.assertTrue(
driver.findElement(By.id("successMessage")).isDisplayed()
);</code></pre>
<hr>
<h2>55. Testing Both Accept and Dismiss</h2>
<p>A complete confirmation-dialog test should consider both possible user decisions.</p>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Scenario</th><th>Action</th><th>Expected Result</th></tr>
<tr><td>Confirm deletion</td><td>Accept</td><td>Record is deleted</td></tr>
<tr><td>Cancel deletion</td><td>Dismiss</td><td>Record remains</td></tr>
</table>
<hr>
<h2>56. Alert Testing Checklist</h2>
<ul>
<li>Verify whether the dialog is a native JavaScript alert.</li>
<li>Identify whether it is an alert, confirm, or prompt.</li>
<li>Trigger the alert through the required application action.</li>
<li>Wait for the alert if necessary.</li>
<li>Switch to the alert.</li>
<li>Read and validate the message.</li>
<li>Accept or dismiss according to the test scenario.</li>
<li>Enter text when the dialog is a prompt.</li>
<li>Verify the resulting page state.</li>
<li>Handle unexpected alerts appropriately.</li>
</ul>
<hr>
<h2>57. JavaScript Alerts vs Synchronization Problems</h2>
<p>An alert-related failure can sometimes look like a synchronization problem. For example, the test may immediately call <code>switchTo().alert()</code> before the application has created the dialog.</p>
<p>Correct approach:</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();</code></pre>
<hr>
<h2>58. Alert Handling with Exception Reporting</h2>
<pre><code>try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Alert: " + alert.getText());
alert.accept();
} catch (TimeoutException e) {
System.out.println("Expected alert did not appear.");
}</code></pre>
<hr>
<h2>59. Native Alert and Browser Context</h2>
<p>A JavaScript alert temporarily takes control of browser interaction. Selenium must interact with the alert before normal page interaction can continue.</p>
<pre><code>Page Context
↓
JavaScript Alert
↓
Alert Context
↓
Accept / Dismiss / Input
↓
Page Context</code></pre>
<hr>
<h2>60. Alert Handling in a Test Framework</h2>
<p>In a framework, alert handling should ideally be centralized through utility methods instead of duplicating low-level alert code in every test.</p>
<pre><code>Test Case
↓
Page Object
↓
Alert Utility
↓
WebDriver Alert API
↓
Browser Dialog</code></pre>
<hr>
<h2>61. Recommended Alert Utility Design</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Utility Method</th><th>Purpose</th></tr>
<tr><td><code>acceptAlert()</code></td><td>Accept current alert</td></tr>
<tr><td><code>dismissAlert()</code></td><td>Dismiss current alert</td></tr>
<tr><td><code>getAlertText()</code></td><td>Read current alert message</td></tr>
<tr><td><code>enterAlertText()</code></td><td>Enter prompt value</td></tr>
<tr><td><code>waitForAlert()</code></td><td>Synchronize with alert appearance</td></tr>
</table>
<hr>
<h2>62. Real-World Example: Delete Confirmation</h2>
<p>Consider an employee management application. When the Delete button is clicked, a confirmation dialog appears.</p>
<pre><code>Click Delete
↓
"Are you sure you want to delete?"
↓
┌───────────────┐
│ │
OK Cancel
│ │
↓ ↓
Delete Record Keep Record</code></pre>
<p>Selenium implementation:</p>
<pre><code>driver.findElement(By.id("delete")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(
message,
"Are you sure you want to delete?"
);
alert.accept();</code></pre>
<hr>
<h2>63. Real-World Example: Invalid Login</h2>
<pre><code>Enter Username
↓
Enter Password
↓
Click Login
↓
Server Validation
↓
JavaScript Alert
↓
Read Error Message
↓
Accept Alert
↓
Verify Login Page</code></pre>
<hr>
<h2>64. Real-World Example: Prompt-Based Input</h2>
<pre><code>Click Enter Name
↓
Prompt Appears
↓
Switch to Alert
↓
Enter Name
↓
Click OK
↓
Application Displays Name
↓
Verify Result</code></pre>
<hr>
<h2>65. Difference Between accept() and dismiss()</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Method</th><th>Typical Meaning</th></tr>
<tr><td><code>accept()</code></td><td>Confirm or click OK</td></tr>
<tr><td><code>dismiss()</code></td><td>Cancel or close the dialog</td></tr>
</table>
<hr>
<h2>66. Difference Between getText() and sendKeys()</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Method</th><th>Purpose</th></tr>
<tr><td><code>getText()</code></td><td>Reads alert text</td></tr>
<tr><td><code>sendKeys()</code></td><td>Enters text into a prompt</td></tr>
</table>
<hr>
<h2>67. Complete Selenium Alert Example</h2>
<pre><code>import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class JavaScriptAlertTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
driver.get("https://example.com");
driver.findElement(By.id("deleteButton")).click();
Alert alert =
wait.until(ExpectedConditions.alertIsPresent());
String actualMessage = alert.getText();
System.out.println("Alert Message: " + actualMessage);
Assert.assertEquals(
actualMessage,
"Are you sure you want to delete?"
);
alert.accept();
driver.quit();
}
}</code></pre>
<hr>
<h2>68. Important Selenium Alert Exceptions</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Exception</th><th>Possible Cause</th></tr>
<tr><td><code>NoAlertPresentException</code></td><td>No alert is available when Selenium tries to access one</td></tr>
<tr><td><code>TimeoutException</code></td><td>Expected alert did not appear within the wait timeout</td></tr>
<tr><td><code>WebDriverException</code></td><td>General WebDriver-related failure</td></tr>
</table>
<hr>
<h2>69. Handling NoAlertPresentException Correctly</h2>
<p>The exception should be handled based on the test requirement. If the alert is mandatory, silently ignoring the exception can hide a real application or automation defect.</p>
<pre><code>try {
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (NoAlertPresentException e) {
Assert.fail("Expected JavaScript alert was not displayed.");
}</code></pre>
<hr>
<h2>70. Handling Alert Timeout Correctly</h2>
<pre><code>try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.accept();
} catch (TimeoutException e) {
Assert.fail("Alert did not appear within expected time.");
}</code></pre>
<hr>
<h2>71. Alert Validation Best Practice</h2>
<p>When the alert message represents an important business requirement, validate it before accepting or dismissing the dialog.</p>
<pre><code>Alert alert = driver.switchTo().alert();
String actualMessage = alert.getText();
Assert.assertEquals(
actualMessage,
"Payment completed successfully"
);
alert.accept();</code></pre>
<hr>
<h2>72. Do Not Use Alerts as Locators</h2>
<p>Alert dialogs do not use standard Selenium locators such as ID, Name, XPath, or CSS Selector in the same way normal DOM elements do.</p>
<p>Incorrect:</p>
<pre><code>driver.findElement(By.xpath("//div[@class='alert']")).click();</code></pre>
<p>For a native JavaScript alert, use:</p>
<pre><code>driver.switchTo().alert().accept();</code></pre>
<hr>
<h2>73. HTML Modal Example</h2>
<p>An HTML modal is different from a JavaScript alert.</p>
<pre><code><div class="modal">
<h2>Delete Record</h2>
<p>Are you sure?</p>
<button id="confirmDelete">Yes</button>
<button id="cancelDelete">No</button>
</div></code></pre>
<p>This can normally be handled with WebElement methods:</p>
<pre><code>driver.findElement(By.id("confirmDelete")).click();</code></pre>
<hr>
<h2>74. How to Identify an Alert</h2>
<p>When testing a web application, determine whether the dialog is:</p>
<ul>
<li>A native JavaScript alert</li>
<li>A JavaScript confirmation dialog</li>
<li>A JavaScript prompt</li>
<li>An HTML/CSS modal</li>
<li>A new browser window</li>
<li>A new browser tab</li>
</ul>
<p>The correct Selenium technique depends on the type of dialog.</p>
<hr>
<h2>75. Alert Handling Decision Table</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Observed UI</th><th>Technique</th></tr>
<tr><td>Native JavaScript alert</td><td><code>switchTo().alert()</code></td></tr>
<tr><td>Native confirmation</td><td><code>alert.accept()</code> / <code>alert.dismiss()</code></td></tr>
<tr><td>Native prompt</td><td><code>alert.sendKeys()</code></td></tr>
<tr><td>HTML modal</td><td>WebElement locator</td></tr>
<tr><td>New tab/window</td><td>Window handles</td></tr>
</table>
<hr>
<h2>76. Alert Handling and Page Object Model</h2>
<p>In a maintainable Selenium framework, the test should focus on business behavior while page objects and utility classes handle implementation details.</p>
<pre><code>Test:
deleteEmployee()
verifyConfirmation()
confirmDeletion()
Page:
clickDelete()
AlertHelper:
waitForAlert()
getAlertText()
acceptAlert()</code></pre>
<hr>
<h2>77. Alert Handling with Assertions</h2>
<pre><code>Alert alert = driver.switchTo().alert();
Assert.assertTrue(
alert.getText().contains("successfully")
);
alert.accept();</code></pre>
<hr>
<h2>78. Contains Validation for Dynamic Alert Text</h2>
<p>If the alert contains dynamic information, exact text matching may not always be appropriate.</p>
<pre><code>String message = alert.getText();
Assert.assertTrue(
message.contains("successfully")
);
alert.accept();</code></pre>
<hr>
<h2>79. Dynamic Alert Message Example</h2>
<p>Suppose an application displays:</p>
<pre><code>Record 1254 deleted successfully</code></pre>
<p>The record number may change. A partial validation can be used when appropriate:</p>
<pre><code>String message = alert.getText();
Assert.assertTrue(
message.contains("deleted successfully")
);
alert.accept();</code></pre>
<hr>
<h2>80. Alert Handling with Logging</h2>
<pre><code>Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println(
"JavaScript Alert Message: " + message
);
alert.accept();
System.out.println(
"JavaScript Alert Accepted"
);</code></pre>
<hr>
<h2>81. Alert Handling in Regression Testing</h2>
<p>JavaScript alert handling is particularly useful in regression suites because confirmation dialogs, validation alerts, and warning messages can appear across many workflows.</p>
<ul>
<li>Login validation</li>
<li>Delete operations</li>
<li>Save operations</li>
<li>Logout confirmation</li>
<li>Payment workflows</li>
<li>Form validation</li>
<li>Session expiration</li>
<li>Administrative actions</li>
</ul>
<hr>
<h2>82. Alert Handling in Data-Driven Testing</h2>
<p>Alert messages and prompt values can also be tested using data-driven approaches.</p>
<pre><code>String[] testInputs = {
"User1",
"User2",
"User3"
};
for (String input : testInputs) {
driver.findElement(By.id("promptButton")).click();
Alert alert = driver.switchTo().alert();
alert.sendKeys(input);
alert.accept();
System.out.println("Tested Input: " + input);
}</code></pre>
<hr>
<h2>83. Alert Handling with Multiple Test Scenarios</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Scenario</th><th>Expected Action</th></tr>
<tr><td>Information alert</td><td>Read and accept</td></tr>
<tr><td>Delete confirmation</td><td>Read and accept</td></tr>
<tr><td>Cancel deletion</td><td>Read and dismiss</td></tr>
<tr><td>Prompt input</td><td>Enter text and accept</td></tr>
<tr><td>Unexpected alert</td><td>Capture and report appropriately</td></tr>
</table>
<hr>
<h2>84. Common Reasons Alert Tests Fail</h2>
<ul>
<li>Alert has not appeared yet.</li>
<li>Test tries to interact with the page while an alert is open.</li>
<li>Incorrect dialog type is assumed.</li>
<li>HTML modal is mistaken for JavaScript alert.</li>
<li>Expected alert text is incorrect.</li>
<li>Prompt input is not supplied.</li>
<li>Alert is already closed.</li>
<li>Test uses unnecessary fixed delays.</li>
<li>Application behavior differs across environments.</li>
</ul>
<hr>
<h2>85. How to Make Alert Tests Stable</h2>
<ol>
<li>Trigger the alert using a deterministic application action.</li>
<li>Use <code>alertIsPresent()</code> when timing is dynamic.</li>
<li>Validate important alert messages.</li>
<li>Handle the alert before continuing page interaction.</li>
<li>Separate alert utilities from test logic.</li>
<li>Avoid unnecessary fixed sleeps.</li>
<li>Capture screenshots or logs when failures occur.</li>
<li>Keep alert handling close to the action that triggers the alert.</li>
</ol>
<hr>
<h2>86. Alert Handling Best Practices for Frameworks</h2>
<ul>
<li>Create reusable alert methods.</li>
<li>Use explicit waits for dynamic alert appearance.</li>
<li>Use meaningful exception messages.</li>
<li>Log alert text when troubleshooting.</li>
<li>Do not silently ignore mandatory alerts.</li>
<li>Keep test assertions close to business requirements.</li>
<li>Distinguish native dialogs from HTML modals.</li>
<li>Keep page objects focused on page behavior.</li>
</ul>
<hr>
<h2>87. Mini Project: Employee Delete Automation</h2>
<p>Build a Selenium automation test for an employee management application.</p>
<p>Requirements:</p>
<ol>
<li>Open the employee application.</li>
<li>Search for an employee.</li>
<li>Click Delete.</li>
<li>Wait for the JavaScript confirmation.</li>
<li>Read the alert message.</li>
<li>Verify the expected message.</li>
<li>Accept the alert.</li>
<li>Verify that the employee is removed.</li>
</ol>
<pre><code>driver.findElement(By.id("deleteEmployee")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
Assert.assertEquals(
message,
"Are you sure you want to delete?"
);
alert.accept();
Assert.assertTrue(
driver.findElement(By.id("deleteSuccess")).isDisplayed()
);</code></pre>
<hr>
<h2>88. Mini Project: Cancel Employee Deletion</h2>
<pre><code>driver.findElement(By.id("deleteEmployee")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.dismiss();
Assert.assertTrue(
driver.findElement(By.id("employeeRecord")).isDisplayed()
);</code></pre>
<hr>
<h2>89. Mini Project: Prompt-Based Registration</h2>
<pre><code>driver.findElement(By.id("enterName")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
alert.sendKeys("Automation Tester");
alert.accept();
String result =
driver.findElement(By.id("displayName")).getText();
Assert.assertEquals(
result,
"Automation Tester"
);</code></pre>
<hr>
<h2>90. Interview Question: What is a JavaScript Alert?</h2>
<p>A JavaScript alert is a browser dialog created by JavaScript that temporarily interrupts normal page interaction. Selenium handles it through the <code>Alert</code> interface rather than treating it as a normal WebElement.</p>
<hr>
<h2>91. Interview Question: How do you handle alerts in Selenium?</h2>
<pre><code>Alert alert = driver.switchTo().alert();
alert.accept();</code></pre>
<p>The <code>Alert</code> interface provides methods for accepting, dismissing, reading text, and entering prompt values.</p>
<hr>
<h2>92. Interview Question: How do you get alert text?</h2>
<pre><code>String message = driver.switchTo().alert().getText();</code></pre>
<hr>
<h2>93. Interview Question: How do you accept an alert?</h2>
<pre><code>driver.switchTo().alert().accept();</code></pre>
<hr>
<h2>94. Interview Question: How do you dismiss a confirmation box?</h2>
<pre><code>driver.switchTo().alert().dismiss();</code></pre>
<hr>
<h2>95. Interview Question: How do you enter text into a JavaScript prompt?</h2>
<pre><code>Alert alert = driver.switchTo().alert();
alert.sendKeys("Test Data");
alert.accept();</code></pre>
<hr>
<h2>96. Interview Question: What exception occurs if there is no alert?</h2>
<p><code>NoAlertPresentException</code> can occur when Selenium attempts to access an alert that is not currently present.</p>
<hr>
<h2>97. Interview Question: How do you wait for an alert?</h2>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.accept();</code></pre>
<hr>
<h2>98. Interview Question: Can Selenium inspect a JavaScript alert using XPath?</h2>
<p>A native JavaScript alert is not handled as a normal DOM element, so XPath is not the standard technique for interacting with it. Selenium's <code>Alert</code> interface should be used.</p>
<hr>
<h2>99. Interview Question: Difference Between Alert and HTML Popup</h2>
<p>A JavaScript alert is a browser-managed dialog handled using <code>driver.switchTo().alert()</code>. An HTML popup or modal is part of the web page DOM and is normally handled using standard WebElement locators.</p>
<hr>
<h2>100. Interview Question: Difference Between accept() and dismiss()</h2>
<p><code>accept()</code> is generally used for OK or confirmation, while <code>dismiss()</code> is generally used for Cancel or rejection.</p>
<hr>
<h2>101. Interview Question: Which Selenium Interface Handles Alerts?</h2>
<p>Selenium Java provides the <code>Alert</code> interface for interacting with JavaScript dialogs.</p>
<hr>
<h2>102. Interview Question: Can You Send Keys to Every Alert?</h2>
<p>No. <code>sendKeys()</code> is intended for prompt dialogs that accept text input. A simple alert normally does not provide an input field.</p>
<hr>
<h2>103. Interview Question: Why Should Explicit Wait Be Used for Dynamic Alerts?</h2>
<p>An alert may not appear immediately after the triggering action. <code>ExpectedConditions.alertIsPresent()</code> allows Selenium to wait for the alert instead of relying on an arbitrary fixed delay.</p>
<hr>
<h2>104. Interview Question: What Happens After Accepting an Alert?</h2>
<p>After the alert is accepted, the browser closes the dialog and Selenium can generally continue interacting with the page.</p>
<hr>
<h2>105. Interview Question: How Do You Test Both OK and Cancel?</h2>
<p>Create separate test scenarios. In one scenario call <code>accept()</code> and verify the confirmation behavior. In another scenario call <code>dismiss()</code> and verify that the operation is cancelled.</p>
<hr>
<h2>106. Quick Revision Table</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Requirement</th><th>Code</th></tr>
<tr><td>Switch to alert</td><td><code>driver.switchTo().alert()</code></td></tr>
<tr><td>Accept</td><td><code>alert.accept()</code></td></tr>
<tr><td>Dismiss</td><td><code>alert.dismiss()</code></td></tr>
<tr><td>Read message</td><td><code>alert.getText()</code></td></tr>
<tr><td>Enter prompt value</td><td><code>alert.sendKeys("value")</code></td></tr>
<tr><td>Wait for alert</td><td><code>ExpectedConditions.alertIsPresent()</code></td></tr>
<tr><td>No alert exception</td><td><code>NoAlertPresentException</code></td></tr>
</table>
<hr>
<h2>107. Alert Handling Cheat Sheet</h2>
<pre><code>// Switch
Alert alert = driver.switchTo().alert();
// Read
String text = alert.getText();
// Accept
alert.accept();
// Dismiss
alert.dismiss();
// Enter prompt text
alert.sendKeys("Test Data");
// Wait for alert
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.alertIsPresent());</code></pre>
<hr>
<h2>108. Practical Learning Sequence</h2>
<ol>
<li>Understand JavaScript <code>alert()</code>.</li>
<li>Understand <code>confirm()</code>.</li>
<li>Understand <code>prompt()</code>.</li>
<li>Learn the Selenium <code>Alert</code> interface.</li>
<li>Practice <code>accept()</code>.</li>
<li>Practice <code>dismiss()</code>.</li>
<li>Practice <code>getText()</code>.</li>
<li>Practice <code>sendKeys()</code>.</li>
<li>Practice explicit waits.</li>
<li>Differentiate JavaScript alerts from HTML modals.</li>
<li>Create reusable alert utilities.</li>
<li>Integrate alert handling with Page Object Model and TestNG.</li>
</ol>
<hr>
<h2>109. Common Mistakes Checklist</h2>
<ul>
<li>Do not use <code>findElement()</code> for a native JavaScript alert.</li>
<li>Do not call alert methods without switching to the alert.</li>
<li>Do not use <code>sendKeys()</code> on a simple alert expecting an input field.</li>
<li>Do not use <code>dismiss()</code> when the test requires confirmation.</li>
<li>Do not ignore mandatory alert failures.</li>
<li>Do not assume every popup is a JavaScript alert.</li>
<li>Do not depend unnecessarily on <code>Thread.sleep()</code>.</li>
<li>Do not forget to validate important alert messages.</li>
</ul>
<hr>
<h2>110. Final Summary</h2>
<p>JavaScript Alerts are an important Selenium WebDriver concept used for automating browser dialogs generated by JavaScript. Selenium provides the <code>Alert</code> interface to interact with these dialogs. The primary operations are switching to the alert, reading its message, accepting it, dismissing it, and entering text into a prompt.</p>
<p>The most important commands are <code>driver.switchTo().alert()</code>, <code>accept()</code>, <code>dismiss()</code>, <code>getText()</code>, and <code>sendKeys()</code>. For dynamically appearing alerts, <code>WebDriverWait</code> with <code>ExpectedConditions.alertIsPresent()</code> provides a more reliable synchronization approach.</p>
<p>Always distinguish native JavaScript alerts from HTML/CSS modals, browser windows, and tabs because each requires a different Selenium handling technique. Proper alert handling makes Selenium automation more stable, maintainable, and suitable for real-world testing scenarios.</p>
<hr>
<h2>111. Selenium Training Resources</h2>
<p>For structured Selenium automation learning, practical projects, Java-based Selenium training, and advanced browser interaction concepts, explore the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Training Course</a>.</p>
<p>To request a course demo, visit the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Course Demo Registration</a>.</p>
</div>