{{announcement.body}}
{{announcement.title}}

Handling Multiple Windows With Protractor For Selenium Testing

DZone 's Guide to

Handling Multiple Windows With Protractor For Selenium Testing

Learn how to handle multiple browser windows and tabs in Protractor framework for Selenium with examples in this complete guide. Read Now!

· Performance Zone ·
Free Resource

Every day is a challenge for newbie automation testers! Just when you learned how to perform automated browser testing on a single window, you now come across the challenge of handling multiple windows. Isn’t this a nightmare! Well, no need to worry, I've got you covered.

slamming head on wall

While performing automated browser testing, at times you might end up in situations where you would need to handle multiple windows and tabs. Your test cases might need you to open a new tab and then switch back to the last window to complete the other pending activities. 

Let’s say you want to check if all the There might be a certain situation when you might come across a situation where the current browser tab is not active. Hence, to find these issues before they hamper your user’s experience, you need to make sure you include all the test cases involving multiple windows/tabs in Selenium with Protractor. 

In this Selenium Protractor tutorial, I'll show you how to handle multiple windows in Selenium with Protractor. If you are not familiar with writing Selenium Automation tests on Protractor, I’ve already covered it in our previous Selenium Protractor tutorial.

Working With Browser Window Handles In Selenium With Protractor

Before we handle browser windows, we need to know how to identify different browser windows and tabs. It’s pretty straightforward, every browser or tab instance has a Global Unique Identifier(GUID), which makes it pretty easy to access them. GUID identifiers help to handle multiple windows, additionally, Protractor provides useful methods that can be used to handle windows. So, let’s have a look at these methods.

getWindowHandle() 

The getWindowHandle() function in the Protractor returns the string GUID for the current active window in the browser. This is invoked on the browser object as - browser.getWindowHandle();

getWindowHandles()

The getWindowHandles() function returns the GUID’s for all the windows and tabs opened on the active browser windows. This is called via the framework as browser.getWindowHandles();

switchTo() 

switchTo() method enables easy management of windows, tabs, and switch between the two. It shifts the control from the current window to the target windows. The GUID is passed as an argument to indicate the Protractor about the target window or tabs. i.e. browser.switchTo().window(guid);

How to Handle Multiple Browser Windows And Tabs In Selenium with Protractor?

Now that you know how to get the GUID of the browser windows and the methods to handle them, you should be fine. So, let’s look at this issue in more detail with a step by step approach to handle multiple windows in the browser.

For ease of understanding, I will start by handling two windows.

Steps To Handle Two Windows In The Browser:

1. First, let’s open the window and launch the URL https://www.lambdatest.com in the browser, to handle multiple windows in Selenium for automated browser testing.

JavaScript
 




x


1
// this property is used to assign an implicit wait time to 20 seconds for automated browser testing  //
2
browser.manage().timeouts().implicitlyWait(20000);
3
 
4
// this functions redirects to the url in the browser for automated browser testing //
5
browser.get(" https://www.lambdatest.com ");
6
 
          



2.  Then by using Protractor’s getWindowHandle() function, I’ll get the GUID of the currently active window and store it into a variable.

JavaScript
 




xxxxxxxxxx
1


 
1
// it fetches the unique identifier for the first window for automated browser testing  //
2
 
3
browser.getWindowHandle().then(function(firstGUID){



3.  Similarly, you can open a new tab/window and navigate to a new URL  e.g. https://www.google.com. Further, by using the sleep method, I can indicate to the Protractor to wait for some time, let’s say 4 seconds, to allow the new tab to load the URL completely. You can even use implicit and explicit wait commands depending on the requirement.

JavaScript
 




xxxxxxxxxx
1


 
1
// it will enable to open the second window with a new url for automated browser testing  //
2
// this functions redirects to the url in the browser //
3
browser.get( " https://www.google.com " );
4
element( by.id("two-window")).click();
5
// make the browser sleep for 4 secs //
6
browser.sleep(4000);



4. Next, I’ll get the GUIDs for both the windows i.e. the first window (parent windows) as well as the seconds' window ( newly opened windows ), using the Protractor’s getWindowHandles() function, which stores the guide values for both windows in a collection Set.

JavaScript
 




xxxxxxxxxx
1


 
1
// it will fetch the unique identifier for all the windows of the browsers for automated browser testing //
2
browser.getAllWindowHandles().then(function(getallGUID){



5. Next, let’s perform an iteration over this collection of GUID, and switch to the new window only after encountering a new GUID, to add to the collection.

JavaScript
 




xxxxxxxxxx
1


 
1
// the for loop iterates over the collection i.e. set of guids //
2
for( var myguid of getallGUID ){
3
    // the conditional statement to check if the identifier is equal to the guid of the first window //
4
    if( myguid != firstGUID ){
5
 
6
    }
7
}



6. Now, I’ll switch to the new window by using the switch().window() function and pass the GUID of the new window as an argument to this function.

JavaScript
 




xxxxxxxxxx
1


 
1
// the switch function shifts the control to the new window //
2
browser.switchTo().window(myguid);
3
// break keyword to come out of the loop //
4
break;
5
 
          



7. Finally, let’s perform a search query on Google, after this, I’ll close the window and return to the previous window.

JavaScript
 




xxxxxxxxxx
1


1
// perform some operation on the new window i.e. searching a keyword on the homepage of google to handle multiple windows in Selenium for automated browser testing//
2
element(by.name("q")).sendKeys("lambda test");
3
 
4
// closes the browser //
5
browser.close();
6
// it switches the control back to the first window //
7
browser.switchTo().window(firstGUID);
8
 
          



In the automation test script below, I’ve taken a test case to show you how to handle and switch between two windows in a browser.

test_config.js

This is the configuration file used by Protractor to manage any config parameter, used globally within the application.

JavaScript
 




xxxxxxxxxx
1
86


1
// test_config.js //
2
// The test_config.js file servers as a configuration file for our test case //
3
// setting required config parameters //
4
exports.config = {
5
   directConnect: true,
6
   // Desired Capabilities that is passed as an argument to the web driver instance.
7
   capabilities: {
8
      'browserName': 'chrome'  // name of the browser used to test //
9
   },
10
   // Flavour of the framework to be used for our test case //
11
   framework: 'jasmine',
12
   // The patterns which are relative to the current working directory when // 
13
Protractor methods are invoked //
14
   specs: ['test_script.js'],
15
// overriding default value of allScriptsTimeout parameter //
16
      allScriptsTimeout: 999999,
17
      jasmineNodeOpts: {
18
// overriding default value of defaultTimeoutInterval parameter //
19
      defaultTimeoutInterval: 999999
20
   },
21
   onPrepare: function () {
22
      browser.manage().window().maximize();
23
      browser.manage().timeouts().implicitlyWait(5000);
24
   }
25
};
26
 
          
27
 
28
var webdriver = require('selenium-webdriver');
29
 
30
var script = require('Protractor');
31
 
32
var driver = new webdriver.Builder().
33
        withCapabilities(webdriver.Capabilities.chrome()).
34
        build();
35
 
36
// describing the test case in Protractor //
37
describe(' Example to demonstrate handle windows in Protractor ', function() {
38
    browser.ignoreSynchronization = true; // to disable sync //
39
   // information about the test case //
40
 it('Scenario to open the Window in browser ', function() {
41
        // this property is used to assign an implicit wait time to 20 seconds //
42
        browser.manage().timeouts().implicitlyWait(20000);
43
        // this function redirects to the url in the browser //
44
        browser.get("https://www.lambdatest.com");
45
        // it fetches the unique identifier for the first window //
46
        browser.getWindowHandle().then(function(firstGUID){
47
            // this opens the new window //
48
            browser.get("https://www.google.com");
49
            element(by.id("two-window")).click();
50
           // make the browser sleep for 4 secs //
51
            browser.sleep(4000);
52
      // it will fetch the unique identifier for all the windows of the browsers to handle multiple windows in Selenium for automated browser testing //
53
            browser.getAllWindowHandles().then(function(getallGUID){
54
            // fetch title of the current page
55
                console.log("The title of the current Page is : "+ browser.getTitle());
56
                console.log("Total number of open Windows : "+getallGUID.length);
57
 
58
  // for loop iterates over the collection i.e. set of guids //
59
                for( var myguid of allGUID ){
60
 // the conditional statement to check if the identifier is equal to the guid of the first window //
61
                    if(myguid != firstGUID){
62
   // the switch function shifts the control to the new window //
63
                   browser.switchTo().window(myguid);
64
    // break keyword to come out of the loop //
65
                        break;
66
                    }
67
                }
68
   // perform some operation on the new window i.e. a search a keyword on the homepage of google //
69
                element(by.name("q")).sendKeys("lambda test");
70
      // fetch the title of the page on the new window //
71
                browser.sleep(5000).then(function(){
72
 console.log(" Title after switching to new window : "+ browser.getTitle());
73
                })
74
       // close the browser //
75
                browser.close();
76
      // again switch back to the parent window //
77
                browser.switchTo().window(parentGUID);
78
           // fetch the tile of the page again //
79
                browser.sleep(5000).then(function(){
80
                    console.log("Page title after switching back to main window: "+ browser.getTitle());
81
                })
82
            })
83
        })
84
    });
85
});
86
 
          



Now let's take a scenario, where you have to handle more than two windows for automated browser testing. This approach is slightly different, I’ll use three windows for Selenium test automation in this case. You can repeat the same process for any number of browsers you want to work with.

Steps to Handle More Than Two Windows In the Browser With Selenium and Protractor

  1. Start with performing  Step 1 to Step 3 from the previous test case.

  2. Now, you already have two tabs, open the third tab, let's open https://www.selenium.dev, and use the sleep function for 4 seconds to wait for the new tab to load completely. 

  3. Now we will store the GUID values for all the three windows in the collection Set  including the value of the newly opened windows using the Protractor’s getWindowHandles() function.

  4. Finally, I'll iterate through the collection and switch to the second tab i.e. https://www.lambdatest.com using the switchTo() method, and then I’ll verify the title of the web page to be  “Cross Browser Testing Tools”.

  5. You can now perform any action on the tab and then close the window to return to the last opened window or tab.

Below is the Selenium test automation script to demonstrate how to handle and switch between more than two windows in a browser in Selenium with Protractor.

JavaScript
 




xxxxxxxxxx
1
48


1
 
2
var webdriver = require('selenium-webdriver');
3
 
4
var script = require('Protractor');
5
 
6
var driver = new webdriver.Builder().
7
        withCapabilities(webdriver.Capabilities.chrome()).
8
        build();
9
 
10
// describing the test case in Selenium with Protractor for automated browser testing//
11
describe(' Example to demonstrate handle windows in Protractor ', function() {
12
    browser.ignoreSynchronization = true; // to disable sync //
13
   // information about the test case //
14
 it('Scenario to open the Window in browser ', function() {
15
        // this property is used to assign an implicit wait time to 20 seconds //
16
        browser.manage().timeouts().implicitlyWait(20000);
17
        // this function redirects to the url in the browser //
18
        browser.get("https://www.lambdatest.com");
19
        // it fetches the unique identifier for the first window //
20
        browser.getWindowHandle().then(function(firstGUID){
21
            // click the button to open new window
22
            element(by.id("three-window")).click();
23
           // make the browser sleep for 4 secs //
24
            browser.sleep(4000);
25
      // it will fetch the unique identifier for all the windows of the browsers for automated browser testing in Selenium with Protractor //
26
            browser.getAllWindowHandles().then(function(getallGUID){
27
            // fetch title of the current page
28
                console.log("The title of the current Page is : "+ browser.getTitle());
29
console.log("Total number of open Windows : "+getallGUID.length);
30
 
31
  // for loop iterates over the collection i.e. set of guids //
32
                for(var myguid of getallGUID){
33
     // verify the title of the page to lambda test
34
                  browser.switchTo().window(myguid);
35
                  browser.getTitle().then(function(title){
36
                    if(title == "Cross Browser Testing Tools"){
37
                        element(by.name("q")).sendKeys("Selenium");
38
                        browser.sleep(4000);
39
 
40
                        }
41
                    })
42
                }
43
                browser.quit()
44
            })
45
        })
46
    });
47
});
48
 
          



Additional Features to Handle Multiple Browser Windows In Selenium With Protractor

The Protractor framework is so robust that it provides various customized utilities that allow us to perform certain actions, by calling its inbuilt classes and functions on the browser object. For instance, imagine a scenario where there is a requirement to open a link in the new window but as a standard protocol, the browser does not allow to open the link in the new window by default. In such a case, we need to force open the link in the new window, using Protractor’s action class.

Below are the steps by step approach to open the link in such a use case :

1. We need to specify the URL we would want to launch ( https:// www.google.com ) and store the element id “force-new-window” for the above link to a variable of type WebElement.

JavaScript
 




xxxxxxxxxx
1


 
1
// store the element
2
WebElement ele = element(By.id("force-new-window")).getWebElement();



2. Next, we will create an object of the action class to invoke certain events on the hyperlink.

JavaScript
 




xxxxxxxxxx
1


 
1
// create object for Actions class
2
browser.actions()
3
 
          



3. Then, we will call various methods on the action class object

  1. Invoke the keyDown () function and pass the Shift key as an argument.

  2. Invoke the click () function and pass the web element from above as an argument.

  3. Finally, we will bind these two methods to the action class using the perform function and our task gets executed. Now we can see the website launched in a new window.

JavaScript
 




xxxxxxxxxx
1


1
browser.actions().keyDown(Protractor.Key.SHIFT)
2
                .click(ele)
3
                .perform()
4
 
          



Below is the complete script that demonstrates how Protractor forcefully launches the link in a new browser window.

JavaScript
 




xxxxxxxxxx
1
28


 
1
var webdriver = require('selenium-webdriver');
2
 
3
var script = require('Protractor');
4
 
5
var driver = new webdriver.Builder().
6
        withCapabilities(webdriver.Capabilities.chrome()).
7
        build();
8
// describing the test case in Protractor //
9
describe(' Example to demonstrate handle windows in Protractor ', function() {
10
    browser.ignoreSynchronization = true; // to disable sync //
11
// information about the test case //
12
    it(' Scenario to open the Window in browser ', function() {
13
        // set the timeout to 20 secs //
14
        browser.manage().timeouts().implicitlyWait(20000);
15
        // launch the url to google.com //
16
        browser.get("https://www.google.com");
17
        // fetch the identifier of the first window //
18
        browser.getWindowHandle().then(function(firstGUID){
19
            // assign the element to a web element type //
20
            WebElement ele = element(by.id("force-new-window"));
21
            // create action object and invoke functions //
22
            browser.actions().keyDown(Protractor.Key.SHIFT)
23
                            .click(ele)
24
                            .perform()
25
        });
26
    });
27
});
28
 
          



Enable Hyperlink to Open in A New Window

Usually, while clicking a hyperlink opens on the same window by default. 

JavaScript
 




xxxxxxxxxx
1


1
<a id='two-window' href='https://google.com'>Click me</a>



But there are certain scenarios when you need the flexibility to open the link in the new windows rather than the same window or tab. This can be done simply by using the anchor tag and setting the value of the target keyword as “_blank”. This ensures that whenever a user clicks on the link, it launches in the new window.

JavaScript
 




xxxxxxxxxx
1


 
1
//this open the url in a new window on clicking the button //
2
<a id='two-window' href='https://google.com' target='_blank'><input type='button' value=" Click to Open New Window"></a>
3
// this launches the link by clicking on the hyperlink //
4
<a id='two-window' href='https://google.com' target='_blank'>Click me</a>
5
 
          



Execute Automation Scripts on Online Selenium Grid Platform With Protractor

You can execute the same Selenium test automation in the cloud Selenium grid platform with minimal configuration changes that are required to build the driver and connect to the LambdaTest hub. Below is the updated script with the required changes

test_config.js

JavaScript
 




xxxxxxxxxx
1
47


 
1
// test_config.js //
2
// The test_config.js file servers as a configuration file for our test case //
3
 
4
LT_USERNAME = process.env.LT_USERNAME || "irohitgoyal"; // Lambda Test User name
5
LT_ACCESS_KEY = process.env.LT_ACCESS_KEY || "r9JhziRaOvd5T4KCJ9ac4fPXEVYlOTealBrADuhdkhbiqVGdBg"; // Lambda Test Access key
6
 
7
exports.capabilities = {
8
  'build': ' Automation Selenium Webdriver Test Script ', // Build Name to be display in the test logs
9
  'name': ' Protractor Selenium Test on Chrome',  // The name of the test to distinguish amongst test cases //
10
  'platform':'Windows 10', //  Name of the Operating System
11
  'browserName': 'chrome', // Name of the browser
12
  'version': '79.0', // browser version to be used
13
  'visual': false,  // flag to check whether to take step by step screenshot
14
  'network':false,  // flag to check whether to capture network logs
15
  'console':false, // flag to check whether to capture console logs.
16
  'tunnel': false // flag to check if it is required to run the localhost through the tunnel
17
  };
18
 
19
// setting required config parameters //
20
exports.config = {
21
   directConnect: true,
22
 
23
   // Desired Capabilities that is passed as an argument to the web driver instance.
24
   capabilities: {
25
      'browserName': 'chrome'  // name of the browser used to test //
26
   },
27
 
28
   // Flavour of the framework to be used for our test case //
29
   framework: 'jasmine',
30
 
31
   // The patterns which are relative to the current working directory when  
32
 
33
Protractor methods are invoked //
34
 
35
   specs: ['test_script.js'],
36
// overriding default value of allScriptsTimeout parameter //
37
      allScriptsTimeout: 999999,
38
      jasmineNodeOpts: {
39
// overriding default value of defaultTimeoutInterval parameter //
40
      defaultTimeoutInterval: 999999
41
   },
42
   onPrepare: function () {
43
      browser.manage().window().maximize();
44
      browser.manage().timeouts().implicitlyWait(5000);
45
   }
46
};
47
 
          



test_script.js

JavaScript
 




xxxxxxxxxx
1
44


 
1
// test_script.js //
2
 
3
// Build the web driver that we will be using in Lambda Test
4
var buildDriver = function(caps) {
5
  return new webdriver.Builder()
6
    .usingServer(
7
      "http://" +
8
      LT_USERNAME +
9
      ":" +
10
      LT_ACCESS_KEY +
11
      "@hub.lambdatest.com/wd/hub"
12
    )
13
    .withCapabilities(caps)
14
    .build();
15
};
16
 
17
// describing our test scenario for Protractor framework //
18
describe(' Example to demonstrate handle windows in Protractor ', function() {
19
    browser.ignoreSynchronization = true; // to disable sync //
20
 
21
// adding the before an event that builds the driver and triggers before the test execution
22
  beforeEach(function(done) {
23
    caps.name = this.currentTest.title;
24
    driver = buildDriver(caps);
25
    done();
26
  });
27
// information about the test case
28
  it(' Scenario to open the Window in browser ', function() {
29
        // set the timeout to 20 secs //
30
        browser.manage().timeouts().implicitlyWait(20000);
31
        // launch the url to google.com //
32
        browser.get("https://www.google.com");
33
        // fetch the identifier of the first window //
34
        browser.getWindowHandle().then(function(firstGUID){
35
            // assign the element to a web element type //
36
            WebElement ele = element(by.id("force-new-window"));
37
            // create action object and invoke functions //
38
            browser.actions().keyDown(Protractor.Key.SHIFT)
39
                            .click(ele)
40
                            .perform()
41
        });
42
    });
43
});
44
 
          



You can execute the Selenium test automation scripts on the cloud, just by adding the desired capability to your code, to connect to the LambdaTest platform. To perform automated browser testing on the cloud Selenium Grid, you need to generate the desired capability matrix to specify the environment you want to execute our Selenium test automation on. Here is the link to visit LambdaTest Selenium desired capabilities generator.

Below is the output on running the Selenium test automation:

To know more about how to handle mouse action and keyboard events in Protractor, refer to our blog on the topic.

Wrapping It Up!

This is just the end of the beginning! You now know how to handle multiple browser windows. Go ahead, and handle the heck out of these browser windows. They might have been a nightmare before, but between you and me, we now know that it's just a piece of cake! You now know how to handle browser windows and tabs in the Protractor framework to perform Selenium Automation Testing. The framework is robust, flexible, and provides various inbuilt classes and functions. 

simple

In case, you want to learn more about using Protractor with Selenium, do subscribe to our blog. And, I’d keep you posted about new blogs. This is certainly not the last blog on Protractor, there’s more to come! If you haven’t checked out our previous blogs on cross-browser testing with a protractor, and Selenium locators with a protractor, debug protractor tests and handling alerts and popups.  I’d urge you to do so, as these topics are essential for automated browser testing. Also, If you’d like to help your peers learn about handling multiple browsers, do share this blog with them. 

That’s all for now!

Happy Testing.

Topics:
javascript, javascript tutorial, performance, protractor, selenium automated testing

Published at DZone with permission of Aditya Dwivedi . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}