JavaScript Pop-ups, Handling Alert Pop-up in Selenium C#

In this tutorial, we will talk about JavaScript Pop-ups and how to handle js popups using the Web Driver of Selenium C#.

What is JavaScript Pop-ups

Generally when we click on any button or an element on the webpage if any message regarding that element or attached with that element so it will appear as a small window or we can say that a Pop-up will appear on our screen.

When we click on the button which is present on the Pop-up so the Pop-up window will disappear. Basically, there are three types of JavaScript Pop-ups –

  • Alert Pop-up: It is used to alert the user.
  • Confirmation Pop-up: Whenever the confirmation is required from the user side this Pop-up is used, usually it is an Alert with”Ok” and “Cancel” buttons.
  • Prompt Pop-up: Whenever some input is required from the user side this Pop-up is used, it is similar to the Confirmation Pop-up along with the additional field where we can supply the input.

In order to use these Pop-ups, we need to use the “IAlert” interface.

How to Handle Alert Pop-up in Selenium C#

In order to handle the Alert, first, we need to switch to alert and for switching the alert we will use a method called “SwitchTo().Alert()” which is coming from the ITargetLocator interface.

So it is similar to like switching from the parent browser window to the child browser window, in order to perform the action on the child browser window.

So once you are successfully switched to the alert you need to call the “Accept()” method which is going to stimulate the clicking “Ok” button at the alert.

So if we go to IWebDriver Interface we have a method called SwitchTo() and inside this, we have an Alert() method which is going to SwitchTo().Alert();  and if we go inside the IAlert interface so as we can see there we have properties and methods in order to handle the JavaScript Pop-ups. Some are mentioned below –

  • Text {get;} : this particular property will return us the text at the Pop-up.
  • Accept(): this method will stimulate the clicking of the “Ok” button at the Pop-up.
  • Dismiss(): it stimulates the clicking of the “Cancel” button at the Pop-up.
  • SendKeys(string KeysToSend): it is used to supply the input at the prompt Pop-up.

So when we say Alert let us see one example of it. This is the webpage, if we click on the “Try it” button

so this Pop-up will appear

this is an example of JavaScript Alert as we can see here it has only the “Ok” button which will be handled using the Accept() method.

So if we don’t handle this Alert properly so our script will fail with further execution. Let’s understand with an example, in TestScript we are going to add one more directory called Popups inside this we will add a class called TestPopups we will make this class public and the attribute will be [TestClass].

Automate JS popup in Selenium C#

[TestClass]
public class TestPopups 
{ 
[TestMethod]
public static void TestAlert()
{
NavigationHelper.NavigateYoUrl("http://www.w3schools.com/js/js popup.asp"); ButtonHelper.ClickButton(By.XPath("//div[@id='main']/descendant::a[position ()=3"));
BrowserHelper.SwitchToWindow(1);
BrowserHelper.SwitchToFrame(By.Id("iframeResult"));
ButtonHelper.ClickButton(By.XPath("//button[text()='Try it']"));
IAlert alert=ObjectRepository.Driver.SwitchTo().Alert();
}
}

So inside this will create a method called TestAlert for navigating to the required webpage where the “Try it” button is present we will copy these 6 lines of code from the TestFrame() method. Now build the solution and run the script in debug mode.

Output: it has hit the debug point then switch to iframe and if we do a stepover again it will click on that button as we can see here we have an Alert Pop-up.

Now in this case, if we don’t handle this Pop-up and again do a stepover so we can see our script is failing with UnhandledAlertException and the reason is the same.

In order to continue the execution with the other statement first, we need to handle this Alert.

Handling of Alert Pop-up

So for handling the Alert we will use the IAlert interface.

[TestClass] 
public class TestPopups 
{  
[TestMethod]  
public static void TestAlert()  
{ NavigationHelper.NavigateYoUrl("http://www.w3schools.com/js/js popup.asp"); ButtonHelper.ClickButton(By.XPath("//div[@id='main']/descendant::a[position ()=3"));   
BrowserHelper.SwitchToWindow(1); BrowserHelper.SwitchToFrame(By.Id("iframeResult"));
ButtonHelper.ClickButton(By.XPath("//button[text()='Try it']")); 
IAlert alert=ObjectRepository.Driver.SwitchTo().Alert();
var text=alert.Text;
alert.Accept();
ObjectRepository.Driver.SwitchTo().DefaultContent();
TextBoxHelper.ClearTextBox(By.Id("textareaCode"));
TextBoxHelper.TypeInTextBox(By.Id("textareaCode"),text);
}
}

So hereafter clicking on that button we will call the method SwitchTo().Alert() and as we know that it will return us the IAlert interface type so we will write IAlert alert=ObjectRepository.Driver.SwitchTo().Alert();

And first, we will get the text so var text= alert.Text; it will give us the text of the Alert box of JavaScript. After that, to click on the Ok button at the Alert we will call alert.Accept();

After that, we will clear this text area and also want to supply the value to this area that is present on the Alert. So here TextBoxHelper.ClearTextBox(By.Id("textareaCode")); then TextBoxHelper.TypeInTextBox(By.Id("textareaCode"),text);

Now again we will run this script in debug mode.

Output: we will do the stepover so it is going to switch to the frame, click on the button to generate the Alert after that it will switch to the Alert so here if the Alert is not present then this method will throw us NoSuchAlertException.

So if we do the stepover it has taken the text from the Alert box.

Now in order to click on this ok button, we will call the Accept() method.

As we can see here now the Alert has gone then switch to DefaultContent,

clear the text area,

and if we do stepover again then it is going to supply the text of the alert box which we have taken to this text area.

Making the Helper class of Alert Pop-up

So inside the ComponentHelper directory, we will add a class called JavaScriptPopHelper and then make this class public. We will add three methods to this.

public class JavaScriptPopHelper
{
public static bool IsPopupPresent()
{
 try  
 {
  ObjectRepository.Driver.SwitchTo().Alert();
   return true;
 }
  catch(NoAlertPresentException)
  {
    return false;
  }
} 
 public static string GetPopUpText()
{ 
 if(! IsPopupPresent()) 
   return "";
 return ObjectRepository.Driver.SwitchTo().Alert().Text;
} 
 public static void ClickOkOnPopup()
{ 
 if(! IsPopupPresent())
       return;
 ObjectRepository.Driver.SwitchTo().Alert().Accept();
}
}

Explanation of code:

First, we are adding a method to check whether the Alert is present or not. Named the method as IsPopupPresent(), make it like  public static bool IsPopupPresent() we will use here the try-catch where we are going to handle only NoAlertPresentException.

so here we will call ObjectRepository.Driver.SwitchTo.Alert(); if this statement is successful we are going to return true and if there is an exception so we will return false.

In the second method, we are using the public static string GetPopUpText() in this first we will check the Pop-up is present so using this we will make the condition false if(! IsPopupPresent()) if this particular statement returns us false then the entire condition will become true and it represents that Pop-up is not there.

So we are going to return the empty string return ""; and if the Pop-up is present so we will return ObjectRepository.Driver.SwitchTo().Alert().Text;

Similarly, the third method is public static void ClickOkOnPopup() here we will use the logic if the Pop-up is not present it is basically returned and if the Pop-up is present then it will click on the “Ok” button by Accept() method.

So after making them in our TestAlert() we will comment out some lines of code

[TestClass] 
public class TestPopups 
{ 
[TestMethod] 
public static void TestAlert() 
{ NavigationHelper.NavigateYoUrl("http://www.w3schools.com/js/js popup.asp"); ButtonHelper.ClickButton(By.XPath("//div[@id='main']/descendant::a[position ()=3")); 
BrowserHelper.SwitchToWindow(1); BrowserHelper.SwitchToFrame(By.Id("iframeResult")); //ButtonHelper.ClickButton(By.XPath("//button[text()='Try it']")); 
//IAlert alert=ObjectRepository.Driver.SwitchTo().Alert(); 
//var text=alert.Text; 
//alert.Accept(); 
var text= JavaScriptPopHelper.GetPopUpText();
JavaScriptPopHelper.ClickOkOnPopup();
ObjectRepository.Driver.SwitchTo().DefaultContent(); TextBoxHelper.ClearTextBox(By.Id("textareaCode")); TextBoxHelper.TypeInTextBox(By.Id("textareaCode"),text); 
} 
}

that we can directly use var text= JavaScriptPopHelper.GetPopUpText(); JavaScriptPopHelper.ClickOkOnPopup(); now we will build this solution and run the script in debug mode.

Output: it has hit the debug point then we will switch to the frame, click on the button, generate the Alert now after this we will call the GetPopUpText() method to get the text of the Alert.

So as we can see there now again we will click on the Ok button of the Pop-up, switch to DefaultContent, clear the text area and supply the text to the other text area.

Now the advantage is that if there is no Pop-up our script will not fail. It returns the text as null and doesn’t perform the click action.

So in this manner, we can handle the Alert with the help of the IAlert interface in the Selenium C# web driver.