# How to Handle JavaScript Alerts with Ocaramba WebDriverExtensions: A Complete Guide

> Master JavaScript alerts in Selenium with Ocaramba WebDriverExtensions. Learn to confirm dismiss or send text to alerts using JavaScriptAlert class for automated testing success.

- Repository: [Accenture/ocaramba](https://github.com/accenture/ocaramba)
- Tags: how-to-guide
- Published: 2026-02-23

---

**Use the `JavaScriptAlert` class via the `WebDriverExtensions.JavaScriptAlert` extension method to encapsulate Selenium alert interactions, then call `ConfirmJavaScriptAlert()`, `DismissJavaScriptAlert()`, or `SendTextToJavaScript()` to handle dialogs with automatic cleanup.**

The **accenture/ocaramba** framework provides a streamlined abstraction layer over Selenium's native alert handling. When you handle JavaScript alerts with Ocaramba WebDriverExtensions, you eliminate boilerplate code for switching contexts and reduce the risk of stale element references in your .NET test automation suites.

## Understanding Ocaramba's JavaScript Alert Architecture

Ocaramba implements a three-layer architecture for alert management that separates concerns between the core wrapper, extension methods, and page objects.

### The JavaScriptAlert Wrapper Class

The **`JavaScriptAlert`** class in [`OcarambaLite/WebElements/JavaScriptAlert.cs`](https://github.com/accenture/ocaramba/blob/main/OcarambaLite/WebElements/JavaScriptAlert.cs) encapsulates all direct interactions with Selenium's `IAlert` interface. It stores a reference to the `IWebDriver`, exposes the alert text via the `JavaScriptText` property, and provides three primary interaction methods:

- **`ConfirmJavaScriptAlert()`** – Clicks the OK button and switches back to default content
- **`DismissJavaScriptAlert()`** – Clicks Cancel and returns to the main document
- **`SendTextToJavaScript(string text)`** – Types into prompt dialogs before accepting

After every action, the wrapper automatically invokes `SwitchTo().DefaultContent()`, preventing stale reference exceptions in subsequent element lookups.

### WebDriverExtensions Extension Method

The fluent API begins with the extension method defined in [`OcarambaLite/Extensions/WebDriverExtensions.cs`](https://github.com/accenture/ocaramba/blob/main/OcarambaLite/Extensions/WebDriverExtensions.cs) (lines 45-53). This adds the **`JavaScriptAlert()`** method to any `IWebDriver` instance:

```csharp
public static JavaScriptAlert JavaScriptAlert(this IWebDriver webDriver)
{
    return new JavaScriptAlert(webDriver);
}

```

This factory pattern enables chainable, readable syntax like `driver.JavaScriptAlert().ConfirmJavaScriptAlert()` without manual instantiation.

### Page Object Integration

Concrete implementations such as `JavaScriptAlertsPage` in the test objects project demonstrate the abstraction in practice. Page objects trigger alerts through UI interactions, then delegate handling to the helper class, keeping test methods focused on business logic rather than Selenium mechanics.

## Step-by-Step Implementation Guide

Follow this workflow to handle JavaScript alerts with Ocaramba WebDriverExtensions in your test projects.

### 1. Trigger the Alert

Locate and click the element that opens the dialog using standard Ocaramba locators:

```csharp
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/javascript_alerts");
driver.GetElement(new ElementLocator(Locator.CssSelector, "button[onclick='jsAlert()']")).Click();

```

### 2. Obtain the Alert Helper

Invoke the extension method to create the wrapper instance:

```csharp
var alert = driver.JavaScriptAlert();

```

### 3. Interact with the Dialog

Choose the appropriate action based on alert type:

```csharp
// Accept a simple alert
alert.ConfirmJavaScriptAlert();

// Or dismiss a confirmation dialog
alert.DismissJavaScriptAlert();

// Or handle a prompt dialog
alert.SendTextToJavaScript("Ocaramba");
alert.ConfirmJavaScriptAlert();

```

### 4. Verify Results (Optional)

Read the alert text before accepting to validate messages:

```csharp
string alertText = alert.JavaScriptText;
// Perform assertions on alertText
alert.ConfirmJavaScriptAlert();

```

## Working with Different Alert Types

Ocaramba's API handles the three standard JavaScript dialog types through consistent methods while managing context switching automatically.

### Simple Alerts (Accept Only)

For basic notification alerts with a single OK button:

```csharp
driver.GetElement(new ElementLocator(Locator.CssSelector, "button[onclick='jsAlert()']")).Click();
driver.JavaScriptAlert().ConfirmJavaScriptAlert();

```

### Confirmation Dialogs (Dismiss)

For dialogs requiring Cancel/No actions:

```csharp
driver.GetElement(new ElementLocator(Locator.CssSelector, "button[onclick='jsConfirm()']")).Click();
driver.JavaScriptAlert().DismissJavaScriptAlert();

```

### Prompt Dialogs (Send Keys)

For input dialogs requiring text entry:

```csharp
driver.GetElement(new ElementLocator(Locator.CssSelector, "button[onclick='jsPrompt()']")).Click();
var alert = driver.JavaScriptAlert();
alert.SendTextToJavaScript("Test Input");
alert.ConfirmJavaScriptAlert();

```

## Page Object Pattern Example

Encapsulate alert interactions within page objects for maintainable test code. The [`JavaScriptAlertsPage.cs`](https://github.com/accenture/ocaramba/blob/main/JavaScriptAlertsPage.cs) implementation demonstrates this pattern:

```csharp
public class JavaScriptAlertsPage : ProjectPageBase
{
    public JavaScriptAlertsPage(DriverContext driverContext) : base(driverContext) { }

    public void OpenJsPrompt()
    {
        this.Driver.GetElement(new ElementLocator(Locator.CssSelector, "button[onclick='jsPrompt()']")).Click();
    }

    public void TypeTextOnAlert(string text)
    {
        this.Driver.JavaScriptAlert().SendTextToJavaScript(text);
    }

    public void AcceptAlert()
    {
        this.Driver.JavaScriptAlert().ConfirmJavaScriptAlert();
    }

    public string ResultText => this.Driver.GetElement(new ElementLocator(Locator.Id, "result")).Text;
}

```

Usage in test methods remains high-level and readable:

```csharp
var jsAlertsPage = new JavaScriptAlertsPage(driverContext);
jsAlertsPage.OpenJsPrompt();
jsAlertsPage.TypeTextOnAlert("Ocaramba");
jsAlertsPage.AcceptAlert();
Assert.AreEqual("You entered: Ocaramba", jsAlertsPage.ResultText);

```

## Summary

- **Use `driver.JavaScriptAlert()`** to obtain the helper instance through the extension method in [`WebDriverExtensions.cs`](https://github.com/accenture/ocaramba/blob/main/WebDriverExtensions.cs)
- **Call `ConfirmJavaScriptAlert()`** to accept, **`DismissJavaScriptAlert()`** to cancel, or **`SendTextToJavaScript()`** to populate prompts
- **Access `JavaScriptText`** to read dialog content before accepting
- **Rely on automatic cleanup**: All methods switch back to default content automatically, preventing stale element exceptions
- **Implement in page objects**: Follow the [`JavaScriptAlertsPage.cs`](https://github.com/accenture/ocaramba/blob/main/JavaScriptAlertsPage.cs) pattern to keep test logic separate from Selenium implementation details

## Frequently Asked Questions

### How does Ocaramba's alert handling differ from raw Selenium WebDriver?

Raw Selenium requires manual `driver.SwitchTo().Alert()` calls and explicit `SwitchTo().DefaultContent()` cleanup after interactions. Ocaramba's `JavaScriptAlert` class encapsulates these switches, reducing code duplication and preventing context-related stale element exceptions by automatically returning to the default content after every action.

### Can I use the JavaScriptAlert helper with multiple consecutive alerts?

Yes, but you must trigger each alert separately. The `JavaScriptAlert` instance remains valid for the driver's lifetime, but you need to invoke the specific UI action that opens each new alert. After handling one dialog, the helper automatically resets to the default content, ready for the next interaction.

### Does the SendTextToJavaScript method automatically accept the prompt?

No, `SendTextToJavaScript(string text)` only populates the input field. You must explicitly call `ConfirmJavaScriptAlert()` afterward to submit the prompt, or `DismissJavaScriptAlert()` to cancel. This separation allows you to verify the entered text via `JavaScriptText` before committing the action.

### Where are the core alert handling files located in the Ocaramba repository?

The primary implementation resides in three locations: [`OcarambaLite/WebElements/JavaScriptAlert.cs`](https://github.com/accenture/ocaramba/blob/main/OcarambaLite/WebElements/JavaScriptAlert.cs) contains the wrapper class, [`OcarambaLite/Extensions/WebDriverExtensions.cs`](https://github.com/accenture/ocaramba/blob/main/OcarambaLite/Extensions/WebDriverExtensions.cs) (lines 45-53) defines the extension method, and [`Ocaramba.Tests.PageObjects/PageObjects/TheInternet/JavaScriptAlertsPage.cs`](https://github.com/accenture/ocaramba/blob/main/Ocaramba.Tests.PageObjects/PageObjects/TheInternet/JavaScriptAlertsPage.cs) provides reference implementations demonstrating page object integration.