Introduction to handle Popup Issues in Selenium
When filling up a form, if we miss filling any mandatory fields, the application will not allow us to proceed. It denotes the error via popup/alert. This article will guide you in detail on how to solve popup related issues in selenium.
Handling Popup is not easy in Selenium. This post talks about handle popup in selenium, code to handle popup in selenium web driver, the command to handle popup in selenium, handle authentication popup in selenium web driver, handle authentication popup in selenium web driver chrome, handle browser popup in selenium, handle certificate popup in selenium, handle download popup in selenium, handle login popup in selenium, handle windows based popup in selenium.
If there is a scenario where we have to download a file, usually we get a pop up asking us to click on open save or exit, this post talks about the approach how to solve this issue using selenium.
When do these alert or popups come?
Alerts or popups actually force the user to shift focus from the current application to the highlighted popup or alert to display the necessary message so that the user can take any corrective measures if required. Mostly user is blocked to do anything until they handle the popup, Below are few commonly observed area due to which popup/alert comes in an application.
- On-webpage load
- On-webpage close
- If the user clicks on a web element
- On right-click on the webpage
- on wrong data entry to the webpage(contact number missing)
- on information save.
- Forgot to accept the terms or conditions of a website.
Alerts/popups are significantly present in online web-based applications, social networking sites, email services, banking applications.
Types of Popups
Before we go deep let us understand how many types of pop up available in the Browser world.
There are mainly 4 types of pop up available.
- JavaScript alert
- Browser Popup
- Native OS popup
- Advanced Javascript Popups
JavaScript alert
Technically an alert is different from popups. Alerts are some sort of message/notification provided to the user about some information. They can act as a warning signal as well. Javascript alert functions are basically the response to an event or a chain of events like- page load, page refresh, user click, mouse move, mouse hover etc
Javascript popup/alert or Browser popups/alerts can be further divided into 3 major categories:
- Simple alert
- Prompt alert
- Confirmation alert
Simple alert
The simple alert is presented to the user with an ok button to notify them about a fact or warning. On Alert, popup users need to click on ok to proceed further. It is one way of communication where the system provides information to the user. The background code is
document.alert("Fix this");
or
alert("fix this");v
A confirmation alert is presented to the user to seek confirmation about a task that the user is going to perform. Like, confirm deletion etc. In confirmation, the popup user needs to select the ok or cancel or yes/no option. Based on the confirmation the application will follow suitable next steps(s).
The background code is as follows:
var confVal=confirm("proceed?");
Why alert is used in an application?
- To convey certain information to users that may be important to them.
- To notify about an error or incorrect data that they have entered.
- To make the user aware of an update.
- To get the attention of the user.
Handling Javascript alert in Selenium
It would be tedious to click on every popup manually. And if at all we are making an end to end script, we do not want manual intervention.
Direct handling of the alert
Incase if your alert support you to inspect and give you the XPath of the close button, you can use the below code:
driver.findElement(By.xpath("//a[@class='xpath of the close button']").click();
Concept of switching in Selenium
During Selenium execution, WebDriver mainly focuses on the main window/main web browser. But when a popup/alert opens, it becomes a new window to the web driver. In order to handle them, you need to switch focus to the new window. This is why selenium provides the below code-
Alert alert = driver.switchTo().alert();
This command takes control from the main window to the new alert window. After switching to the child alert window, we can handle it, the control automatically sets to parent window/main window.
Using Selenium’s Alert interface
Selenium supports a wide range of functionalities and methods to resolve alert related issues. Now Selenium can really handle Javascript and Browser popup. Selenium has full control over them. For this, we need to use the Alert interface(org.openqa.selenium.Alert) and its methods to perform various operations. Alert acts as a bridge between GUI and the actual web page.
To handle alert related tasks, we need to import the corresponding package by the following code-
import org.openqa.selenium.Alert;
Now there are different methods available to handle the popup.
Method | Description | Example |
---|---|---|
void accept() | ok button of the alert is clicked | driver.switchTo().alert().accept(); |
void dismiss() | cancel button of the alert is clicked | driver.switchTo().alert().dismiss(); |
String getText() | Captures the text present in the alert box | driver.switchTo().alert().getText(); |
void sendKeys(String str) | Send some text to the alert box. It is particularly helpful if the button has some hotkeys associated with it. Prompt alerts can also be resolved by this function. | driver.switchTo().alert().sendKeys(String str) |
void setCredentials(Credentials credentials) | sets the given credentials to the alert | driver.switchTo().alert().setCredentials(Credentials credentials) |
void authenticateUsing(Credentials credentials) | Authenticate an HTTP based authentication dialog | driver.switchTo().alert().authenticateUsing(Credentials credentials) |
Web/Browser based alerts are called javascript alerts. Using the above methods, Javascript and browser popups can be handled properly. Selenium provides APIs to handle JavaScript PopUps out of the box.
Alert alert = driver.switchTo().alert();
alert.accept();
Using JavacsriptExecutor
WebElement targetElement=driver.findElement(By.id('the target element'));
((JavascriptExecutor)driver).executeScript("arguments[0].clcik(),targetElement);
Alert myAlert=(Alert)driver.switchTo().alert();
String myText=myAlert.getText();
myAlert.sendKeys("A");
myAlert.accept();
Note- driver.accept() or driver.dismiss() etc can work for javascript based popups but not for jQuery based popups or PhantomJs based Popups.
.
Custom method to check if an alert is present?
The custom method detects the presence of the alert and accordingly, the subsequent code can handle it.
public boolean isAlertPresent(){
try{
driver.switchTo().alert();
return true;
}
catch(Exception e)
{
return false;
}
}
and inside your code the remaining code will be as follows:
if(isAlertPresent()){
driver.switchTo().alert();
driver.swtchTo().alert().accept();
driver.switchTo().defaultContext();
}
Acknowledgement of alert using assert
There are two ways to actually acknowledge an simple alert
- assertAlert(pattern)- This method asserts that the alert is present if it matches the pattern with the alert text. If a match is found the script will continue to execute.
- assetAlertPresent()- This method dismisses the alert and continues the execution. It does not need any matching with text and pattern.
There are three ways to actually acknowledge a confirmation alert
- assertConfirmation(pattern)- This method asserts that the confirmation is present if it matches the pattern with the confirmation text. If a match is found the script will continue to execute. otherwise, it will throw a milestone error event.
- assetConfirmationPresent()-This method dismisses the alert and continues the execution. It does not need any matching with text and pattern.
- chooseCancelOnNextConfirmation- This method also cancels the confirmation by clicking on the cancel button if next time any javascript confirmation alert comes.
There are three ways to actually acknowledge a prompt alert
- answerOnNextPrompt(answer)- This asset function fills the textbox of the next prompt. In case this method is not used when the next prompt is acknowledged then the default text for the same prompt is accepted.
- assertPrompt(pattern)- This method asserts that the prompt is present if it matches the pattern with the confirmation text. If a match is found the script will continue to execute. otherwise, it will throw a milestone error event. This method also provides input text to answerOnNextPrompt() method.
- assetPromptPresent()-This method accepts the prompt and continues the execution. It does not need any matching with text and pattern. This method also provides input to the answerOnNextPrompt() method.
Hidden Divison Popups
Hidden Divison Popups are new era’s popups. These popups are gaining huge popularity nowadays. The alert is actually hidden inside the HTML source code of the webpage. There are preset trigger tab or mechanism to activate them. Popups related to contact forms, error message are the most suitable alert of the hidden division category.
Features of Hidden Division Popups
- These popups are not related to javascript popup.
- They are mostly modal in nature but many of them do not allow users to perform anything on the web page until the user handles them.
- These popups are inspectable in the developer console.
- These popups are resizable and extensively customizable.
- These popups may contain scrollbars(horizontal or vertical) to display the extended contents.
- They are generally locked in a single space as a result user can not move them.
- They can be integrated with another version of popups or can be chained with another popup with the initial alert dialog.
- These popups are very colourful.
- Finally, if they are not handled properly via selenium, selenium can throw ElementNotClickableError.
How to resolve Hidden division alerts/popups?
driver.findElement(By.xpath("Xpath_of_the_target_element)).click();
Frame popup
The switching concept works for the frame as well. The switching is used to handle frame related popups.
driver.switchTo().frame(param)
The param may take either of the below three
- a number- frames are indexed based(starts with zero). In case the page has four frames the first frame always has index=0 and the fourth one is having index=3. You need to switch to frame (a particular one) then all subsequent calls can be made on that.
driver.switchTo().frame(index);
- a name/id- Frames can also be identified by their name or id. this id is not similar to the index. These are explicitly set by the developers. However, note that frames having names is given higher priority over frames with id.
driver.switchTo().frame("id/name");
- a webelement Frames can also be indentified by using a previously found/known element.
driver.switchTo().frame(iFrame anElement);
Note once we switch to a new frame and once we are done with the operation, we need to switch back to the original or default context to access elements of the other frames.
driver.switchTo().defaultContent();
PopUps- Windows Popup
Popup is another flavour of interruption but technically they are coming from Windows. It can also occur due to some activity done by the user. These alerts are system generated and coders take the help of the system APIs to display the message to the users.
Selenium WebDriver mostly can not resolve the Windows popups or alert directly. We have several approached to handle them. For Native popups, we need to take different approaches. One approach is given here to exclude these test cases. It may be possible to convince the customer about the downside of this problem.
Primary type of window popups are:
- File upload
- File download
- Window popup
- child browser
- Dialogue popup
- Authentication popup
- Hidden division
- Calendar popups
File upload Popup
This popup comes in a dynamic webpage or website when a user tries to upload a certain file to the website. It seeks permission to access the local storage in order to browse the files from the disk. The upload popup consists of the browse/choose option(with an editable/non-editable textbox to provide the path). Once the user clicks on the browse button/tab this triggers to open this popup.
The user needs to select the file and click on the ok button. The path of the file that is selected, is set to the text box. The user then needs to click on the upload button to upload the same file into the application.
driver.findElement(by.name("upload")).sendkeys("c:\test\abc.txt");
driver.findElement(by.name("upload")).click();
in case this does not work, check out the other strategies like AutoIT, Robot, Sikuli area.
Authentication Popup
Authentication is a process to access some secure application. It uses an HTTP authentication mechanism. Mostly they are server-side validation. The clientside(browser) upon involving some secure application prompts the authentication dialog box as part of the basic security. It helps the application to get rid of the unauthorized access. These kinds of popups are used to authenticate a user like a password-protected webpage.
Features of Authentication popups
- The GUI of the popup is heavily customizable.
- Depending on browser configuration the popup can be moved or can not be moved by the user.
- The original underlying webpage can only be accessed if the user provides valid credentials.
- Generally, as soon as the webpage loads the popup appears.
- The elements of the authentication popup are not inspectable.
How to solve authentication popup
driver.get(protocol://username:[email protected]);
//you can turn off synchronization further
//or you can use the follwoing
Alert.authenticateUsing(Credentials credentials);
disable authentication popup in chrome using config
- Open config.js file
- update capabilities in the same file as below:
Capabilities:{
'browserName':'chrome',
'chromeOptions:{
args:["user_data_dir=c:\\Users\\{userName}\\AppData\\Local\\Chrome\\UserData\\Default"],
},
},
With this configuration, if you execute the script, the authentication popup will be automatically handled.
But if at all we need to perform this operation we may take the following approaches.
The approaches available are:
- Disable Popup
- Using Window handles
- Using Profile
- Preference
- Using Sikuli
- Using AutoIT
- Using Robot
Disable Popup
In this approach, we disable the popup from the browser setting and command what’s to be done. We need to download it. We provide that here and give a path where we need to download. During the run after this step, We copy the downloaded file to our required path. During run popup will not open rather file will be downloaded to the path given. More detailed steps can be found here
Handling the notification related popups
Notifications are also one-way communication and mostly carry not much value while testing. To handle it, we can suppress it beforehand.
To disable popups in Firefox
- Select Tools from the Mozilla Firefox taskbar
- Select Options from the drop-down menu
- Select Content from the Options dialog box
- To disable all pop-ups, check the Block pop-up windows radio button
- Select Close
To disable popups in Google Chrome
- Click the Chrome menu
- on the browser toolbar.
- Select Settings.
- Click Show advanced settings.
- in the “Privacy” section, click the Content settings button.
To disable popups in Internet Explorer
- Click Tools menu
- Press Alt-T if you don’t see a menu
- Click Internet Options
- Click the Privacy tab
- Under Pop-up Blocker, Check Turn on Pop-up Blocker
- Click OK
Handling Push notification, geolocation, permission popups
If these are not important for your testing, you can still disable them.
By manually disable
- On your computer, open Chrome.
- At the top right, click More. Settings.
- At the bottom, click Advanced.
- Under “Privacy and security,” click Site settings.
- Click Notifications.
- Choose to block or allow notifications: Block all: Turn off Ask before sending.
By using code in Chrome
ChromeOption class is specially designed for chrome browser and driver. It provides the best results when combined with DesiredCapabilities.
ChromeOptions are best suited for handling
- geolocation popups
- automation information related popups
- Push notification popups
Using ChromeOption class. We can disable some of the options there and finally pass this to WebDriver to act and open the browser with these options.
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-geolocation");
ChromeDriver driver = new ChromeDriver(options);
//disable notification
options.addArguments("--disable-notifications");
//or beyond chome version 50
Map<string Object> myPreferences=new HashMap();
myPreferences.put("profile.default_Content_Setting_Values.notification",2);
ChromeOptions myOptions=new ChromeOptions();
myOptions.setExperimentalOption("prefs",myPreferences);
WebDriver driver=new ChromeDriver(myOptions)
By using code in Firefox
For firefox, this can be done using a preference setting dom.disable_open_during_load in the Firefox profile from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("dom.disable_open_during_load", False)
driver = webdriver.Firefox(firefox_profile=profile)
Disabling Popup blocker in InternetExplorer
This can be done by setting a registry setting.
from _winreg import *
def set_popupblocker_status(enabled):
key = OpenKey(HKEY_CURRENT_USER, r"Software\Microsoft\Internet Explorer\New Windows", 0, KEY_ALL_ACCESS)
SetValueEx(key, "PopupMgr", 0, REG_SZ, enabled)
CloseKey(key)
set_popupblocker_status("no")
Using Window handles
To handle the popups this is one of the best strategies. Selenium provides two methods to handle popups
- driver.getWindowHandles()-Selenium web driver assigns each web browser opened by it with a unique alphanumeric id called window handle. This method returns the window handles of the already opened popups. We can traverse between windows by the window handles. It returns a list of all the opened windows related to the driver. The return type is Set. Set is a collection that grows dynamically but does not contain any duplicate value. Set eliminates the duplicate instances of the window with the same identification id if there are any duplicate instance present.
- driver.getWindowHandle()- This method returns the window handle of the current window within the driver instance. This is a unique number(globally unique identifier-GID) that can distinguish other windows from the current ones. It actually returns an id by which the driver identifies the window. The return type is String. We can use this id as a reference to switch between multiple windows.
To iterate over window handles, we can use the two strategies
- While loop
- For each loop
The corresponding code is as follows for the While loop
.....
....
//your initial code
//just before the click code where the window popup comes..
String mainWindowHandle=driver.getWindowHandle();
//now write the code of the click that brings the popup.
Set<String> allWindowHandles=driver.getWindowHandles();
Iterator<String> ite=allWindowHandles.iterator();
String newPopupWindowHandle;
while(ite.hasNext()){
newPopupWindowHandle=ite.next().toString();
if(!newPopupWindowHandle.equals(mainWindowHandle))
{
driver.switchTo().window(newPopupWindowHandle);
//perform the required code to handle the new popup
}
}
The corresponding code is as follows for the For each loop
String mainWindowHandle=driver.getWindowHandle();
//code to get the popup window
Set allWindowHandles=driver.getWindowHandles();
for(String sub:allWindowHandles){
if(!sub.equalsIgnoreCase(mainWindowHandle))
{
driver.switchTo().window(sub);
//perform the required code to handle the new popup
}
Another approach
Set allHandles=driver.getWindowHandles();
ArrayList myList=new ArrayList(allHandles);
String parentID=myList.get(0);
String childID=myList.get(1);
How to check the presence of dynamic window popups?
Using Set and with the help of a customized function, we can determine if the popup came dynamically.
public boolean isPopupCame()
{
Set<String> allWindowIds=driver.getWindowHandles();
if(allWindowIds.size()>1){
return true;
}
else{
return false;
}
}
Using the Profile option
Some use the profiler concept to handle download popup. The code will look like below:
FirefoxProfile profile = new FirefoxProfile();
String path = "D:\Download\";
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", path);
profile.setPreference("browser.download.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsksaveToDisk", "application/x-msexcel,application/excel,application/x-excel,application/excel,application/x-excel,application/excel,application/vnd.ms-excel,application/x-excel,application/x-msexcel");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", false);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
WebDriver driver = new FirefoxDriver(profile);
It is described here. But many times it failed.
Using the Preference option
The Code will be
profile.set_preference("browser.download.panel.shown", False)
profile.set_preference("browser.helperApps.neverAsk.openFile","text/csv,application/vnd.ms-excel")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/vnd.ms-excel")
profile.set_preference("browser.download.folderList", 2);
profile.set_preference("browser.download.dir", "c:\firefox_downloads\")
browser = webdriver.WebDriver(firefox_profile=profile)
It is described here
Using Sikuli
Sikuli is another very popular alternative to AutoIT. It works on Image-based comparison between the actual and expected window. It then performs as per recording. It is an open-source tool that helps to automate window-based applications, web applications and gaming. to use sikuli with Selenium, you need to download and attach sikulixapi.jar in your project.
public class WebdriverSikuli {
private WebDriver driver;
private String baseUrl;
private Screen screen;
@BeforeSuite
public void setUp() throws Exception {
driver = new FirefoxDriver();
screen = new Screen();
//Give link of the URL from where the download starts
baseUrl = "download URL";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testUntitled() throws Exception {
driver.get(baseUrl + "/");
//Give cordinates where it needs to go
driver.findElement(By.linkText("20.30.0")).click();
screen.click("images/SaveFileButton.png");
}
@AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
}
Using Robot
This is applicable when the interaction is very limited. Using Robot class we can simulate KeyPress, Tabkeys, Mouse move etc. But all events happen either on the keyboard or based on on-screen coordinates. So can perform on a single screen resolution. A slight difference in screen resolution may fail test execution.
It depends on the focus too. If Focus got shifted from one place to another before invoking this method. It is bound to fail.No String support for keyboard event. It can throw only one character at a time. So it is a little time-consuming.
It can not capture the property value of the popup like title, String inside the popup. So no custom approach can be taken based on the failure message of the popup. It handles all pop up in the same way. A detailed approach can be found here.
Handling via Robot class requires two basic packages. Here is the code to import them into your project-
import java.awt.Robot;
import java.awt.event.keyEvent;
Note while working with Robot class, we generally use thread.sleep(XX) instead of WebDriver wait. The Robot class can simulate keyboard and mouse events. java.awt.event.keyEvent lets the user to use keyPress and keyRelease events from the keyboard.
Robot myRobot=new Robot();
myRobot.mouseMove(x,y);//move the courser to the close button of the popup
myRobot.keyPress(keyEvent.VK_D);
myRobot.keyRelease(keyEvent.VK_D);
in some cases, while the popup comes, control needs to be transferred to the popup in order to perform the required click operation. In that case, we need to take help of the action class.
Action myAction=new Action(driver);
myAction.moveToEmenet(targetElement).build().perform();
// now code to handle the popup
Incase your alert supports and respond to escape character, you can use keyPress(Escape) to resolve the alert.
The issue with Robot class:
In general Robot class works well. But while the script runs in a different box with different resolution, due to pixel difference or position changes due to monitor size, the x,y coordinate changes, The mouse move operation fails to target the required position. The script fails.
Using AutoIT
AutoIT is one of the open source tools that can automate the operation of the window. it creates an executable script that can be called from selenium. It is based on image comparison. During the creation of the script, we provide the popup picture and asks it to compare for the same image during runtime.
If matches then it performs the set of operations we want it to do. This method is highly dependent on Screen resolution, So it will work exactly the same or greater resolution not lesser resolution. However, AutoIT is the best available tool to handle windows dialogue or popups. AutoIT can handle modal dialogue boxes, save dialogue boxes, Username and password dialogue boxes.
AutoIt is a free scripting language designed to automate the window component. It is similar to extensive VB Script and allows us to convert the script to an executable(.exe) More details can be found here. AutoIT provides a command to handle popup in selenium or provides ways to handle windows based popup in selenium.
The major components of AutoIT are:
- AutoIt script editor(SciTE)
- Spy or Finder tool
The steps are:
- Download AutoIT from the site
- Install It
- Open the SciTE editor and using the record option you can create the required steps.
- The script needs to be saved as FileName.au3
- Convert the script to an executable File- name FileName.exe
To execute the AutoIt script we need to use the following command:
Process process=new Process("path_of_the_.exe","path_of_the_file_to_be_uploaded","open").start();
//or
Runtime.getRuntime(path_FileName.exe);
xdoTool
In Linux, in order to automate Linux based application, we can take the help of xdotool. It is very similar to AutoIt or Sikuli but can simulate only keyboard inputs and mouse movements. Using this we can manipulate Linux based applications.
Using WinAppDriver
WinAppDriver is another addition to automating windows related automation via Selenium. To work with WinAppDriver, it is better to install the Windows SDK. Combined, they can inspect a window popup and can create code to handle popups with Selenium.
WinAppdriver can automate the followings:
- UWP- Universal Windows Platform based applications
- WinForms- Windows Form-based applications
- WPF-Windows Presentation Foundation based applications
- Win32- Classic windows based applications.
The main component is inspect.exe. To activate inspect.exe, you need windows SDK. Using this tool, you can inspect any windows based applications and their building components.
Supported locator strategies are:
- Xpath
- Name
- Accessibility
- Automation id
- Class
- Tagname(localized control type)
Dynamic Alert or Popup
Dynamic alerts/popups do not show up every time during the manual/automation way of surfing. They may come due to some processing error or some other reasons or at a random interval. In case, we expect a popup, we will code accordingly, the script may fail due to the unavailability of the popup. On the other hand, if we do not expect the popup, we do not accordingly, the script will fail. So we have to be extra careful while dealing with dynamic alerts or unexpected alert popups.
How to resolve dynamic alert/popups in Selenium
Unexpected popups/alerts can be of two types, javascript-based popups/alerts or Native OS-based popups. In the above section, we have learned how to solve popups/alerts of different types in several different mechanisms. now understand, not all dynamic popups can be handled but we can identify the faulty areas where the random popups are coming. Accordingly, we can cover them under the try-catch block of java exception handling. The best practice is to put the error-prone code inside the try-catch block in the below manner.
......
.....
//your initial code
try{
driver.findElemnet(By.id("ElementID")).click();
WebDriverWait wait=new WebDriverWait(driver,10);
wait.until(ExpectedConditions.alertIsPreseent());
Alert myAlert=driver.switchTo().alert();
myAlert.accept();//alert came
}
catch(Exception e){
//alert did not come
}
.....
.....
//your next set of code
Herein case the alert is present the try-catch will accept the alert else it will generate the required exception and proceed with the test execution.
How to automate Captcha popups?
Captcha is not intended to be automated so technically via selenium, we directly can not automate it. However, using OCR jars few captchas can be automated.
The second approach to set the captcha code in a field of the captcha component. This is only for testing instance. using the getText() method of the component, we can retrieve the value and go past the step.
The third approach to use some professional captcha services like DeathByCaptcha. Note this is expensive as you have to buy the license for your testing.
import com.DeathByCaptcha.AccessDeniedException;
import com.DeathByCaptcha.Captcha;
import com.DeathByCaptcha.Client;
import com.DeathByCaptcha.SocketClient;
import com.DeathByCaptcha.HttpClient;
/* Put your DeathByCaptcha account username and password here.
Use HttpClient for HTTP API. */
Client client = (Client)new SocketClient(username, password);
try {
double balance = client.getBalance();
/* Put your CAPTCHA file name, or file object, or arbitrary input stream,
or an array of bytes, and optional solving timeout (in seconds) here: */
Captcha captcha = client.decode(captchaFileName, timeout);
if (null != captcha) {
/* The CAPTCHA was solved; captcha.id property holds its numeric ID,
and captcha.text holds its text. */
System.out.println("CAPTCHA " + captcha.id + " solved: " + captcha.text);
if (/* check if the CAPTCHA was incorrectly solved */) {
client.report(captcha);
}
}
} catch (AccessDeniedException e) {
/* Access to DBC API denied, check your credentials and/or balance */
}
Exception related to popup
Alerts if not appear, the script will throw an exception called NoAlertPresentException.You can either throw it by declaring with the test method and with the throw clause. like-
public void myMethod() throws NoAlertPresentException
or can handle with try-catch block. NoAlertPresentException is present inside org.openqa.selenium.NoAlertPresentException package. To work with the same, you need to import the package into your code.
Too many Popups? Not good for real life.
To start with it is not common behaviour for any good and legit website to take(rather hijack) control your web browser. If it happens, it is the fault of the developers. It must be caught during the manual or functional testing of the application. It is not a good candidate for automation. If your test environment or any other environment does this, you can raise a bug and put the site into the blocked list.
Secondly, any alert/popup should not maximize or can not put you into an infinite loop. In case you are constantly getting new tabs without your permission, your browser may also have been infected with malware, trojans or some malicious code.
Note advertise windows are also popup windows. incase if you don’t need them, you can safely block them.
Modal or non-modal? A serious question
Before handling any popup during script development, you need to understand what kind of popup it is. It can be iFrame or modal or windows native popup.
In the case, of the modal dialog box, either we need to wait for sometimes(10-20 seconds) to work further. Also, you need to check if it is click trapped modal. In that case, the execution control can no come out from the parent window to switch to the child popup.
Modal popups are built using the client-side javascript framework like Bootstrap, Reactjs etc. The difference between a normal alert and a modal alert depends on the backend implementation.
In general, a normal popup needs to be handled and a user can not do anything without responding to that alert/popup. In modal, it is in general made of <div> tag accompanied with some CSS code. User can click on anywhere in the window and can go to any other page other than the modal alert.
Conclusion
Most popups are designed in such a way that it blocks the user’s screen. The user can not do anything or any other operations until they handle these popups. All these popups and alerts are used to warn users about their recent actions an the application or seek permission or information to carry out the next steps.
I hope that most of the popups in your application are solved by using one of the techniques listed above. Most interestingly the new generation javascript popups can also be handled with these techniques. You need to be patient and understand what works well for you. Also, note if you are using a protractor, these techniques works.