Saturday, 27 April 2013

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.

<html>
<head>
<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?");
  }
}
</script>
</head>
</head>
<body>
<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"/>
<br/>
First name: <input type="text" name="firstname" id="firstname"/><br />
Last name: <input type="text" name="lastname" id="lastname"/>
</body>
</form>
</html>

Below selenium code handles these popups.

Alert Box:

Global.selenium.chooseOkOnNextConfirmation();
Global.selenium.click("alert");
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.

Confirmation: 
Global.selenium.chooseOkOnNextConfirmation();
Global.selenium.click("confirm");
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

Prompt:
Global.selenium.chooseOkOnNextConfirmation();
Global.selenium.click("prompt");
System.out.println("Clicked on OK button in confirm box");
String prompt=Global.selenium.getPrompt();
Global.selenium.type("firstname""hiiii");
Thread.sleep(10000);

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

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...