Search This Blog

Wednesday, November 9, 2011

Handling alert, prompt and confirmation box using Selenium RC

This article explain about how to deal with java script alert, prompt and confirmation box.

Copy below html code and save it as test.html.

<script type="text/javascript">

function show_alert()
alert("I am an alert box!");
function show_confirm()
var r=confirm("Press a button");

function show_prompt()
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
  document.write("Hello " + name + "! How are you today?");
<form action="">
<input type="button" onclick="show_alert()" value="Show alert box" id="alert"/>
<input type="button" onclick="show_prompt()" value="Show prompt box" id="prompt"/>
<input type="button" onclick="show_confirm()" value="Show confirm box" id="confirm"/>
First name: <input type="text" name="firstname" id="firstname"/><br />
Last name: <input type="text" name="lastname" id="lastname"/>

Below selenium code handles these popups.

Alert Box:

System.out.println("Clicked on OK button in alert box");
String alert=Global.selenium.getAlert();//This is needed as If an confirmation is generated but you do not consume it with getConfirmation, the next Selenium action will fail.
Global.selenium.type("lastname", "venkat");
Thread.sleep(10000); //just for to see actions by selenium. Not needed 

Same way you can handle both prompt and confirmation boxes.

System.out.println("Clicked on OK button in confirm box");
String confirmation=Global.selenium.getConfirmation
Global.selenium.type("firstname", "fname");
Thread.sleep(10000);//just for to see actions by selenium. Not needed

System.out.println("Clicked on OK button in confirm box");
String prompt=Global.selenium.getPrompt();
Global.selenium.type("firstname", "hiiii");

Tow points to remember are :

  1. Note that your first statement should be chooseOkOnNextConfirmation(), before clicking on an element which generates alert or popup
  2. GetAlert(), GetConfirmation() and GetPrompt(); commands should be issued after alert or popup has been generated, else subsequent statements will be failed.

No comments:

Post a Comment