How to Handle JavaScript Alerts with Ocaramba WebDriverExtensions: A Complete Guide
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 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 contentDismissJavaScriptAlert()– Clicks Cancel and returns to the main documentSendTextToJavaScript(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 (lines 45-53). This adds the JavaScriptAlert() method to any IWebDriver instance:
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:
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:
var alert = driver.JavaScriptAlert();
3. Interact with the Dialog
Choose the appropriate action based on alert type:
// 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:
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:
driver.GetElement(new ElementLocator(Locator.CssSelector, "button[onclick='jsAlert()']")).Click();
driver.JavaScriptAlert().ConfirmJavaScriptAlert();
Confirmation Dialogs (Dismiss)
For dialogs requiring Cancel/No actions:
driver.GetElement(new ElementLocator(Locator.CssSelector, "button[onclick='jsConfirm()']")).Click();
driver.JavaScriptAlert().DismissJavaScriptAlert();
Prompt Dialogs (Send Keys)
For input dialogs requiring text entry:
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 implementation demonstrates this pattern:
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:
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 inWebDriverExtensions.cs - Call
ConfirmJavaScriptAlert()to accept,DismissJavaScriptAlert()to cancel, orSendTextToJavaScript()to populate prompts - Access
JavaScriptTextto 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.cspattern 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 contains the wrapper class, OcarambaLite/Extensions/WebDriverExtensions.cs (lines 45-53) defines the extension method, and Ocaramba.Tests.PageObjects/PageObjects/TheInternet/JavaScriptAlertsPage.cs provides reference implementations demonstrating page object integration.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →