How to handle Modal Dialog Box in Selenium Webdriver.

What is Modal Dialog Box?
Function Modal Dialog Box is used to deal with Modal Type Windows.
When we open a window using this function Java-script execution gets suspended till the window gets closed.
Here parent window is expecting some return value from the pop-up window.
So the problem in Selenium Web-driver is that when we open a Modal window then accessibility to the parent window is Blocked.

Problem in Selenium with Modal Dialog Box.
Selenium works with Java-script. When show Modal dialog is called Javascript gets suspended from the parent.
Selenium whose handle still pointing to the Main window gets suspended.
As a result all the successive commands after that gets suspended.

How to handle Modal Dialog Box in Selenium Web-driver.
Pre-requisite: I believe when a Modal Dialog Box is opened then the cursor is on the Modal Dialog Box.
In that case we can handle the operation on the Modal Dialog Box using Robot class.

Lets say Below is a screen-shoot of one the Modal Dialog Box where it accepts a String and after pressing an Enter key its gets close.

 After we perform the action which opens Modal Dialog box, Try below Method
       

 Robot robot = new Robot();  
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
StringSelection data_to_enter= new StringSelection("Data to Enter");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(data_to_enter, null);
Thread.sleep(7000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

In StringSelection enter the Data which is required to be sent in the text-field on Modal Dialog Box and it will save that string into system’s clip board and next action will paste that string at the cursor position.
The Rest actions are handled by Robot class which will pass the key events in the manner .(cntrl + V, Enter).

Let me know if you find the above implementation useful in your code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s