TESTEROPS

A pragmatic approach to QA and OPS

Handling JavaScript Alerts

In today’s world, it is silly and naive to think of a webpage not implementing JavaScript. Even the smallest of webpage will be executing a small code of Javascript in it.

One of the most common ways in which JavaScript is present on the web page is in terms of Alerts, Pop-Ups and Confirmation boxes. These are the basic types of JavaScript alerts that most web page incorporate. You must have had encountered these kinds of alert boxes in real life, on the internet. A good example is when you delete all items from a e-commerce application, it always prompts a message asking for confirmation that you really want to delete all the items from the cart. That alert or confirmation box is a type of JavaScript alert that we are talking about here.

A simple example can be found out here. Now JS Alerts and Pop-ups are one of the most annoying things that we need to handle when we are going to test a web page using Selenium. However if you know how to handle it, then it becomes it very easy to handle it.

We’re going to handle three different types of JS Alerts :

  • Simple JS Alert
  • A Confirmation Box
  • A JS Prompt

Let us see how we are going to handle all these three types of Alerts.

Handling JS Alert

A Simple JS Alert looks like this :

alert

In case such a scenario, we need to switch to this alert first and then click on the OK button. For doing this we need to use switch_to.alert  property. Then we will use the accept( )
method to accept the alert or in simple words we will click on the OK button.

__author__ = 'rahul'

import unittest
from selenium import webdriver


class JSAlertCheck(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_JSAlert(self):
        driver = self.driver
        driver.maximize_window()
        driver.get('http://the-internet.herokuapp.com/javascript_alerts?__s=xg1k6kuwg5ks2nkp3wfa&utm_campaign=elemental-selenium-ruby&utm_medium=email&utm_source=51-javascript-alerts')

       #this searches for for the first alert button and clicks on that
        btn1=driver.find_elements_by_css_selector('button')[1]
        btn1.click()

       #now we switch to alert
        popup = driver.switch_to.alert

       #use the accept() method to accept the alert
        popup.accept()
        
       #this gets the result text returned
        textreturned = driver.find_element_by_id('result')

        print(textreturned.text)
        
       #we assert if the text returned is what we wanted
        self.assertTrue(textreturned.text,"You Clicked: OK")

    def tearDown(self):
           self.driver.quit()


if __name__ == '__main__':
    unittest.main()

Now we would see how we are going to handle another kind of JavaScript alert- the Confirmation Alert.

Handling JS Confirmation Alerts

This is what a JS Confirmation Alert looks like

confirm

This is handled in the same way as the JS Alert that we handled above. The only difference is that we also have a dismiss( ) method in case we want to cancel the alert.

__author__ = 'rahul'

import unittest
from selenium import webdriver


class JSAlertConfirm(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
    def test_JSAlertConfirm(self):
        driver = self.driver
        driver.maximize_window()
        driver.get('http://the-internet.herokuapp.com/javascript_alerts?__s=xg1k6kuwg5ks2nkp3wfa&utm_campaign=elemental-selenium-ruby&utm_medium=email&utm_source=51-javascript-alerts')
     
        #get the second button by xpath and click on it
        btn2 = driver.find_element_by_xpath("//*[@id='content']/div/ul/li[2]/button")

        btn2.click()

        #switch to the alert
        jsalert= driver.switch_to.alert
        
        #accept the alert
        jsalert.accept()
  
       #get the resultant text and assert if it is same as we want
        textReturned = driver.find_element_by_id('result')

        print(textReturned.text)

        self.assertTrue(textReturned.text, 'You Clicked: Ok')


        #refresh the webpage
        driver.refresh()
 
        #get the button again and click on it
        btn2 = driver.find_element_by_xpath("//*[@id='content']/div/ul/li[2]/button")

        btn2.click()

       #switch to alert
        jsalert = driver.switch_to.alert

       #to cancel the alert, we need to use dismiss( ) method
        jsalert.dismiss()

       #get the resultant text and assert if it is same as we expect.
        textReturned2 = driver.find_element_by_id('result')

        print(textReturned2.text)

        self.assertTrue(textReturned2.text,'You Clicked: Cancel')




    def tearDown(self):
        self.driver.quit()


if __name__ == '__main__':
    unittest.main()

The third type of alert that we’re gonna handle is the JS Prompt.

Handling JS Prompt Box

This is what a JS Prompt box looks like

prompt

JS Prompt allows to allow some text to be entered in the alert. This is also same as the other two alerts, the only other exception being that if you want so custom text to enter in the prompt, you need to switch to the alert and then use the send_keys( ) method to send the required text. Let us see how we do that.

__author__ = 'rahul'

import unittest
from selenium import webdriver

class JSPrompt(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_JSPrompt(self):
        driver = self.driver
        driver.maximize_window()
        driver.get('http://the-internet.herokuapp.com/javascript_alerts?__s=xg1k6kuwg5ks2nkp3wfa&utm_campaign=elemental-selenium-ruby&utm_medium=email&utm_source=51-javascript-alerts')

       #get the third button by using it's xpath and click on it
        btn3 = driver.find_element_by_xpath("//*[@id='content']/div/ul/li[3]/button")
        btn3.click()
  
       #switch to the alert
        jsprompt= driver.switch_to.alert

       #send custom text to the prompt using send_keys( ) method
        jsprompt.send_keys('Rahul')

        #accept the alert
        jsprompt.accept()

        #assert that the result returned is what we expected
        textReturned = driver.find_element_by_id('result')

        print(textReturned.text)

        self.assertTrue(textReturned.text,'You entered: Rahul')

    def tearDown(self):
        self.driver.quit()


if __name__ == '__main__':
    unittest.main()

So these are the three main types of alerts that we need to handle while working with web pages. Now we have another type of alert, which are window-based JS alerts- an example is when you try to attach something to your gmail, then a window based pop-up opens up. We can handle that too, but that can be handled using different methods, which we will try to work out later.

In the next section, we will learn about another wonderful JS mechanism that we use in Selenium- the JavaScriptExecutor.

3 thoughts on “Handling JavaScript Alerts

  1. Question: for ‘Handling the JS Prompt Box’solution, you are using: jsprompt.send_keys(‘Rahul’)

    However, despite the test completing successfully, it doesn’t appear that ‘Rahul’ is actually being sent. If you add a sleep before the alert accept, you’ll see no entry being made.

    Is this the expected result?

    Tks!

    Like

Leave a Reply to rydv09 Cancel 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: