Skip to content
CodeKruPro

Accept a simple alert and read its text

Automation taskEasy-MediumAsked in: Capgemini, Infosys, TCS, Wipro

Interviewers ask: "How do you handle a JavaScript alert?" Switch to it, read its text, accept it. The browser draws the alert outside the page, so normal locators cannot reach it.

Handle Simple Alert

Handle Simple Alert

JavaScript alerts are handled using driver.switchTo().alert(). A simple alert has text and an OK button.

Methods:

  • alert.getText() - get alert message
  • alert.accept() - click OK
  • alert.dismiss() - click Cancel (for confirm/prompt)

Task:

  1. Navigate to https://testkru.com/Interactions/Alerts
  2. Click the "Show Alert" button
  3. Switch to the alert, get its text
  4. Accept (dismiss) the alert
  5. Print the alert text

Expected output:

Alert text: This is a simple alert!