Skip to main content

Handling Dialogs in Selenium Automation


According to me Selenium is one of the best open source, free tool for testing web applications. It's quite powerful and gives you the facility to write down your test case in your favorite language ( from the plenty of languages it supports ). But it sucks when it comes to handle the dialogs. Dialog boxes are like ghosts to selenium, It can't even see them.

That's because dialogs are native to the operating system you are running and selenium are designed to identify only web component.

After searching too much on the Internet and other forums, I finally got the solution to all my problems. The solution is too simple. As you can't handle the dialog box through selenium, use the other software to do this. And AutoIT is best at this.

Download Execuable (exe) to Handle Save Dialog of Firefox

Download Execuable (exe) to Handle Save Dialog of Internet Explorer

Download Execuable (exe) to Handle Authentication Dialog


User Name and password dialog box


AutoIt
Autoit is a free scripting language designed to automate the windows component. It's just like an extensive VB Script and it allows you to convert the script in executable (exe). So what you can do is, write down the script to handle dialog box using AutoIt, convert it into executable and then call the executable when required. So let's see guys how to do it. But before we begin you need to downloadand install the Autoit. Download it from the following link
Download AutoIt


Handling alertbox
Alertbox is special kind of modal dialog created though JavaScript. As it's modal dialog box the things in the parent window will not be accessible until close it.

selenium provides the method to handle the alertbox, It will click on the OK button of the alertbox and will return the text of the alertbox to verify. However it will not able to identify the alertbox if it has appeared through page load event. ( i.e. should not appeared when you navigate to site or when refresh it).


Handle Alertbox at page load event
Selenium is not able to indentify the dialogs appeard at the pageload event. look at this.

So we tried to click on the OK button with AutoIt script. I make the Autoit script, not a big was just three line code and tested it with both the browser and it did well. But when I call the same script (exe) from my testcase it fails to indentify the alertbox and my testcase failed. I am still finding out why the hell this is happening.
Following is the script to handle alertbox appeard at body load event.


AutoItSetOption("WinTitleMatchMode","2")
WinWait($CmdLine[1])
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
MsgBox(0,"",$title)
WinActivate($title)
WinClose($title);


Confirmbox
Confirm box is a kind of alertbox with OK and Cancel button as compared to only OK button in alerbox.
Selenium provides following APIs to handle this.

chooseOkOnNextConfirmation() - This will click on the OK button if the confirm box appears after executing the very next step.
chooseCancelOnNextConfirmation() - This will click on the cancel button if the confirm box appears after executing the very next step.

You need to write down any of the above functions (depends on you requirement, ofcourse) just before the step which opens the confirmbox.

import org.testng.annotations.*;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class Handle_Alert {
   private Selenium selenium;
  @BeforeClass
    public void startSelenium() {
    selenium = new DefaultSelenium("localhost", 4444, "*chrome","http://gaurangnshah.googlepages.com/");
    selenium.start();
  }
@AfterClass(alwaysRun=true)
 public void stopSelenium() {
   this.selenium.stop();
  }
@Test
public void handleAlert() throws Exception{
  selenium.open("selenium_test");
  selenium.click("Alert");
  String a = selenium.getAlert();
  System.out.println(a);
 }

@Test
public void handleConfirmBox() throws Exception {
selenium.open("selenium_test");
selenium.chooseCancelOnNextConfirmation();
selenium.click("Confirm");
}

}


Handing Modal Dialogs
Modal Dialog box mean once it has appeared all the focus of that application will be on that dialog box only. You will not able to access any of the other component of parent window until you close the dialog box.

Some of the modal dialog boxes that we face frequently during web application testing are


Save Dialog Box
Save dialog box is bit different in IE and in Firefox. So I have write down two separate script for that.

AutoIt script to handle Firefox Save Dialog box
In Firefox when you click on the button/link to download a file. First it will ask you for you permission once you select yes, If you have selected to ask you for the path then only a dialog box will display.

If you will click on download link following dialogbox will appear in Firfox.

If you click "Save File" on above dialogbox this dialog box will apppears, Yeah if you have choose to ask where to save file from Option.

The executable and the script below will handle both of these dialogboxes. You just need to call it in proper way. Your need to pass arguments while calling the script or executable as following.
Save_Dialog_FF Operation FilePath
Operaion: Operation you want to perform when dialog box appears. Can be any of the following
cancel: Press Cancel on the dialog box
Save: Press the Save as Dialog box
FilePath: It's an option argument. It's a full path where you want to save the file.

i.e. C:\myfile.txt


AutoItSetOption("WinTitleMatchMode","2")
if $CmdLine[0] < 2 then
msgbox(0,"Error","Supply all the Arguments, Dialog title,Save/Cancel and Path to save(optional)")
Exit
EndIf


WinWait($CmdLine[1]) ; match the window with substring
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
WinActive($title);
If (StringCompare($CmdLine[2],"Save",0) = 0) Then
WinActivate($title)
WinWaitActive($title)
Sleep(1)
send("{TAB}")
Send("{ENTER}")
if ( StringCompare(WinGetTitle("[active]"),$title,0) = 0 ) Then
WinActivate($title)
send("{TAB}")
Send("{ENTER}")
EndIf

if WinExists("Enter name") Then
$title = WinGetTitle("Enter name")
if($CmdLine[0] = 2) Then
WinActivate($title)
ControlClick($title,"","Button2")
Else
WinActivate($title)
WinWaitActive($title)
ControlSetText($title,"","Edit1",$CmdLine[3])
ControlClick($title,"","Button2")
EndIf

Else
Exit
EndIf

EndIf

If (StringCompare($CmdLine[2],"Cancel",0) = 0) Then
WinWaitActive($title)
Send("{ESCAPE}")
EndIf


Now you just need to copy and paste above scripts in Autoit IDE, convert those into executables, Save those to the project folder. And then just make a call to the executables with proper arguments, just before you execute the step which invokes the dialog box as shows here.


import org.testng.annotations.*;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;


public class Handle_Dialogs {
private Selenium selenium;
@BeforeClass
public void startSelenium() {
selenium = new DefaultSelenium("localhost", 4444, "*chrome","http://www.autoitscript.com/");
selenium.start();
}

@AfterClass(alwaysRun=true)
  public void stopSelenium() {
 this.selenium.stop();
}


@Test
public void handleSaveDialog() throws Exception {
String[] dialog;
selenium.open("/site/autoit/downloads/");
selenium.waitForPageToLoad("3000");
selenium.click("//img[@alt='Download AutoIt']");
Thread.sleep(2000);
String browser = selenium.getEval("navigator.userAgent");
if(browser.contains("IE")){
System.out.print("Browser= IE "+browser);
dialog = new String[]{ "Save_Dialog_IE.exe","Download","Save" };
Runtime.getRuntime().exec(dialog);
}

if(browser.contains("Firefox")){
System.out.print("Browser= Firefox "+browser);
dialog = new String[] { "Save_Dialog_FF.exe","Opening","save" };
Runtime.getRuntime().exec(dialog);
  }
 }
}


User Name and Password Dialog Box.

Following is the AutoIt script to handle to User name and password dialog box.

AutoItSetOption("WinTitleMatchMode","2")
if $CmdLine[0] < 3 then
msgbox(0,"Error","Supply all the Arguments, Dialog title User Name, Password")
Exit
EndIf


WinWait($CmdLine[1]) ; match the window with substring
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
ControlSend($title,"","Edit2",$CmdLine[2]);Sets User Name
ControlSend($title,"","Edit3",$CmdLine[3]);Sets Password
ControlClick($title,"","OK");



Thanks to Gaurang Shah for this post.....

Comments

Popular posts from this blog

Some good Resources / Blogs / Sites for Selenium Users

Here I have listed out some good blogs and sites by extensive selenium automation users. Hope these will help you a lot. http://automationtricks.blogspot.com  - by NirajKumar http://www.theautomatedtester.co.uk/ http://testerinyou.blogspot.com   - by Naga/Mathu http://seleniumready.blogspot.com  - by Farheen Khan http://seleniumdeal.blogspot.com/  - Amit Vibhuti http://seleniumexamples.com/blog Sauce Labs and BrowserMob are companies doing cloud and extensive selenium automation services, products, etc http://saucelabs.com/blog http://blog.browsermob.com http://testingbot.com/ Cedric Beust -  creator of the TestNG Java testing framework. http://beust.com/weblog/ http://blog.reallysimplethoughts.com/  - by Samit Badle, Created many Selenium IDE Plug-Ins Available Colud Testing: 1. SauceLabs 2. Soasta 3. BrowserMob 4. CloudTesting.com  etc. Selenium Testing Products: 1. Twist by ThoughtWorks 2.  TestMaker by  PushToTest 3. Element34 company providi

UFT - Take full page screenshot by scrolling the page

'######################################################################################## 'This is navigate through the full page and taking individual screenshot of visible area '######################################################################################## Function TakeScreenshot Dim intScrolls, intScroll, strScrollPos Set pgApp = Browser ( " " ) .Page ( " " ) intScrolls = Round ( pgApp . RunScript ( " document.documentElement.scrollHeight / (screen.height) " ) , 2 ) If intScrolls < 1 Then intScrolls = - 1 pgApp . RunScript " window.scrollTo(0, 0); " Wait 1 Browser ( " " ) .CaptureBitmap " C:\screenshot0.png " , True For intScroll = 0 To intScrolls If Environment . Value ( " Browser " ) = " CHROME " Then strScrollPos = " scrollY " Else strScrollPos = " document.documentElement.scrollTop " End If If p

Change IE Browser ZOOM settings

Lot of UI automation testers could have faced this problem as we could change the zoom settings while operating manually for our convenience and forgot to reset to 100%. But our QTP and some other related tools would operate the browser perfectly if browser zoom is 100%. So wee need to change the zoom before start to run the scripts. Its better to have a code snippet in our framework to change this zoom setting right? Here we go... 1. We can simply change the Registry values before Invoking IE Function  ChangeRegistry   Dim  objShell   Set  objShell =  CreateObject ( "WScript.Shell" )  objShell.RegWrite  "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Zoom\ZoomFactor" ,  "100000" ,  "REG_DWORD"   Set  objShell =  Nothing End   Function This option is very useful. But in real time, lot of customers could have restricted write access to windows registry. So we can try other options. 2. Use IE COM object and Change