Handling JavaScript Alerts & Browser Pop-Ups
Why Alerts Need Special Handling
JavaScript alerts, confirms, and prompts are rendered by the browser itself, not the web page's DOM. This means Selenium can't locate or click them using normal element locators - they require a dedicated switch_to.alert interface instead.
Types of JavaScript Pop-Ups
| Pop-Up Type | Purpose |
|---|---|
| Alert | Displays a message with a single OK button |
| Confirm | Asks the user to accept or cancel an action |
| Prompt | Asks the user to enter text input before continuing |
Common Alert-Handling Methods
Once Selenium switches focus to the alert, a small set of methods covers nearly every interaction you'll need to perform with it.
- driver.switch_to.alert - shifts control to the currently open alert
- alert.accept() - clicks OK or accepts the alert
- alert.dismiss() - clicks Cancel or dismisses the alert
- alert.send_keys() - types text into a prompt-style alert
- alert.text - reads the message displayed in the alert
A Note on Native Browser Pop-Ups
Native browser pop-ups, such as permission requests for location or notifications, aren't part of the page's HTML and generally can't be controlled through standard Selenium commands - they usually need to be disabled via browser configuration instead.
Alerts are one kind of context switch - the other common one is moving between multiple windows and embedded frames.
Ready to master Selenium Training Course?
Join Uncodemy's hands-on training and build real automation skills with expert mentors.
← Back to Course