Browser Windows/Tabs handling in Protractor | browser.switchTo.window() (2022)

Table of content

  • Multiple Windows in Protractor
  • Multiple Windows
  • Get Window Handles in protractor
  • Handle simple Two Browser Windows / Tabs
  • More than Two Windows handling
  • How does the developer make the link to open in New Window
  • Force to open in new Window rather than Tab

Multiple Windows in Protractor

There will be times when you will be required to perform some testing, where the testing operations open a new browser window /tab, a test case may require you to perform some tasks on the

newly opened browser window/tab

and return back to the original window to perform the remaining tasks.

Even if the window/tab is currently on focus, but still, it is not an active window, so to perform some tasks, you need to switch to a new browser window/tab in protractor.

Commands will have an effect on the base window unless we switch our control to a new window/tab.

Previously tab and Windows are two different items, as tabs do not have any GU iD. Now developers made tab and windows to have GUIDs, so tabs and windows are treated as same in protractor.

Situations when we are likely to deal with multiple windows:

  • Filling forms may require selecting the date from a separately opened window
  • Clicking on some link/button can open another window
  • Handling Advertisement windows

Handle iFrame with Protractor

Multiple Windows

Browser Windows/Tabs handling in Protractor | browser.switchTo.window() (1)

Above image depicts multiple browser windows

  • Our Application is opened on Parent/Base window, the total number of windows is one
  • When clicking on a link/button our application opens two new windows along with base window, now the total number of windows present is Three (base + child-1 + child-2)
  • Now move to Child-1 window and perform click on a button/link which opens another one more window along with child-window, now the total number of windows is 4 (base + child-1 + child-2 + grand child-1)
  • We can perform an operation on the grandchild -1 window, and we can close all windows or specific windows.

If we perform the above operation manually, we may not find difficulty, but handling the above scenario is tricky in protractor

Send emails in protractor

Get Window Handles in protractor

protractor provides few methods to handle the multiple windows; let's see what the methods and their uses are.

GU ID:
GU ID abbreviation of Globally Unique Identifier, Every OS generates GU ID for application to identifying them uniquely. We will be using this GU ID to handle the multiple browsers; GU ID is a numeric string value.

8589934593


getWindowHandle() :
getWindowHandle method in protractor returns the current(active) browser's GU ID. It returns GU ID as string value.

browser.getWindowHandle();


getWindowHandle() :
getWindowHandles method in protractor returns GU ID of all the browsers present at the moment, which are opened by the current browser object. This method returns GU IDs as Set of String.

browser.getWindowHandles();

List Collection in Typescript : List is one of the Collection types, and it stores the values at sequential places in memory.

We can access the values based on the index as List stores values in sequential places ( this is one of the major differences between List and Set).

We must not access the windows based on the index because you might not know which windows is stored at what place, because protractor adds window ID based on what time they appeared. So accessing windows based on the index may give the wrong window.

switchTo().window() : switchTo() method in protractor helps user to switch between windows, frames, elements, alerts.

switchTo().window(GU ID) method switches the control from the current browser window to the target browser window, which has the specified "GU ID".

browser.switchTo().window(guid);

Javascript to select dropdown option

Handle simple Two Browser Windows / Tabs

Click the button to open a new window ( google.com)

Please use Firefox as the browser to open the link in a new window; if you use chrome, the link may be opened in a new tab rather than a new window.
Browser Windows/Tabs handling in Protractor | browser.switchTo.window() (2)

Steps to Handle Two Windows :
1. Open firefox browser and Navigate to https://chercher.tech/protractor/handle-browser-windows-protractor

// set implicit time to 30 secondsbrowser.manage().timeouts().implicitlyWait(30000);// navigate to the urlbrowser.get("https://chercher.tech/protractor/handle-browser-windows-protractor");


2. Get the GU ID of the current (parent) window using getWindowHandle() method present in the protractor and store the value in a String

// get the Session id of the Parentbrowser.getWindowHandle().then(function(parentGUID){


3. Click on the Open New Window button, application open new window with google page. Make the protractor to sleep for 5 seconds; otherwise, it may not find the newly opened tab.

// click the button to open new windowelement(by.id("two-window")).click();browser.sleep(5000);


4. Get the GU IDs of the two windows (parent + google), using the getWindowHandles() method present in the Protractor. Store the GU IDs in a Set Collection; this Set will have GU IDs of both parent and Child Browsers

// get the All the session id of the browsersbrowser.getAllWindowHandles().then(function(allGUID){


5. iterate the Set of GUID values, and if the value is parent value skip it if not switch to the new window

// iterate the values in the setfor(let guid of allGUID){// one enter into if block if the GUID is not equal to parent window's GUIDif(guid !=parentGUID){}}


6. Switch to the window using switchTo().window() method present in protractor, pass the GU ID of the child browser to this method.

// switch to the guidbrowser.switchTo().window(guid);// break the loopbreak;


7. Find the search bar in Google.com and search for "success"

// search on the google pageelement(by.name("q")).sendKeys("success");


Close the Google tab/Window and return to parent tab/browser window

// close the browserbrowser.close();// switch back to the parent windowbrowser.switchTo().window(parentGUID);

Complete code for switching window may look like below

import { browser, element, by, ExpectedConditions, protractor} from 'protractor'import { Alert } from 'selenium-webdriver';describe('Protractor Typescript Demo', function() {browser.ignoreSynchronization = true; // for non-angular websitesit('Browser Window Operation', function() {// set implicit time to 30 secondsbrowser.manage().timeouts().implicitlyWait(30000);// navigate to the urlbrowser.get("https://chercher.tech/protractor/handle-browser-windows-protractor");// get the Session id of the Parentbrowser.getWindowHandle().then(function(parentGUID){// click the button to open new windowelement(by.id("two-window")).click();browser.sleep(5000);// get the All the session id of the browsersbrowser.getAllWindowHandles().then(function(allGUID){// print the title of th epageconsole.log("Page title before Switching : "+ browser.getTitle());console.log("Total Windows : "+allGUID.length);// iterate the values in the setfor(let guid of allGUID){// one enter into if blobk if the GUID is not equal to parent window's GUIDif(guid !=parentGUID){// switch to the guidbrowser.switchTo().window(guid);// break the loopbreak;}}// search on the google pageelement(by.name("q")).sendKeys("success");// print the title after switchingbrowser.sleep(5000).then(function(){console.log("Page title after Switching to goolge : "+ browser.getTitle());})// close the browserbrowser.close();// switch back to the parent windowbrowser.switchTo().window(parentGUID);// print the titlebrowser.sleep(5000).then(function(){console.log("Page title after switching back to Parent: "+ browser.getTitle());})})})});});

I have not resolved the promises of the getTitle(), so you might see the manage promise message instead of text Browser Windows/Tabs handling in Protractor | browser.switchTo.window() (3)

JSON format Logging using winston in Protractor

More than Two Windows handling

We have handled the two windows in the above tutorial by comparing GUID, but when we have more than two windows, we cannot use the same approach. To access the exact page, we may need the title of the page, based on the title of the page we can differentiate the browser windows in selenium.

Tip : We can use the title, URL, element reference while switching into a new window to ensure that we are switching to the required window. I prefer Title, URL than an element

Scenario : Click on the Open 3 New Windows button, it will open three more windows (bing, google, yahoo), now switch to Bing and search for "gates". Browser Windows/Tabs handling in Protractor | browser.switchTo.window() (4) Steps to Handle More than Two Windows :

  • 1. Open Firefox browser and Navigate to https://chercher.tech/protractor/handle-browser-windows-protractor
  • 2. Get the GU ID of the current (parent) window using getWindowHandle() method present in the protractor and store the value in a String
  • 3. Click on the Open 3 New Window button, application open new window with google page. Make the protractor to sleep for 5 seconds; otherwise, it may not find the newly opened tab.
  • 4. Get the GU IDs of the two windows (parent + google + bing + yahoo), using the getWindowHandles() method present in the Selenium webdriver. Store the GU IDs in a Set Collection; this Set will have GU IDs of both parent and Child Browsers
  • 5. Now iterate through the List, and switch to the first GUID in Set and check the page title contains the keyword "bing".

Complete program for switching multiple windows in protractor

import { browser, element, by, ExpectedConditions, protractor} from 'protractor'import { Alert } from 'selenium-webdriver';describe('Protractor Typescript Demo', function() {browser.ignoreSynchronization = true; // for non-angular websitesit('Browser Window Operation', function() {// set implicit time to 30 secondsbrowser.manage().timeouts().implicitlyWait(30000);// navigate to the urlbrowser.get("https://chercher.tech/protractor/handle-browser-windows-protractor");// get the Session id of the Parentbrowser.getWindowHandle().then(function(parentGUID){// click the button to open new windowelement(by.id("three-window")).click();browser.sleep(5000);// get the All the session id of the browsersbrowser.getAllWindowHandles().then(function(allGUID){// print the title of th epageconsole.log("Page title before Switching : "+ browser.getTitle());console.log("Total Windows : "+allGUID.length);// iterate the values in the setfor(let guid of allGUID){// check the title of the page to match with "bing"browser.switchTo().window(guid);browser.getTitle().then(function(title){if(title == "Google"){element(by.name("q")).sendKeys("gates");browser.sleep(5000);}})}browser.quit()})})});});

Components of Cookies

How does the developer make the link to open in New Window

The developer can make the link to open in a new window using the target keyword present in anchor tag <a>, when developer set this value to "_blank", the link will be opened in new windows when user clicks the link.

// button is nested inside a link<a id='two-window' href='https://google.com' target='_blank'> <input type='button' value="Open New Window"></a>// plain link<a id='two-window' href='https://google.com' target='_blank'>Click me</a>


If the developer avoids using target='_blank', the browser opens such links in the same window. It is recommended not to open the link in a new window.

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

Install Protractor + Jasmine + Typescript + VSCode + NodeJs [Free Tools]

Force to open in new Window rather than Tab

There will be situations where we have to open a link in the new Window, but later browser does not support opening a URL in the new window as it is not recommended ( phishing is easy with new windows ).

During such scenarios, we can use action class to open the link in a new window by pressing the Shift key, and to click the link; it opens the link in a new window in protractor.

Steps to open link in a new Window :

  • Open the Firefox browser and navigate to https://chercher.tech/protractor/handle-browser-windows-protractor
  • 2. Find the above link using id force-new-window and store it in a variable of WebElement type
    // store the elementlet ele:WebElement = element(By.id("force-new-window")).getWebElement();
  • 3. Create an object for Actions class
    // create object for Actions classbrowser.actions()
  • 4. Call keyDown() method from the Actions class object and pass Keys.SHIFT as parameter
  • 5. Call Click() method from the Actions class object, pass the stored web element as a parameter to this method
  • 6. Use perform() method from Actions class object to bind the keyDown() and click() methods and to perform the operations.
    browser.actions().keyDown(protractor.Key.SHIFT).click(ele).perform()

Complete program for opening a link in a new window in protractor.

import { browser, element, by, ExpectedConditions, protractor} from 'protractor'import { Alert, WebElement } from 'selenium-webdriver';describe('Protractor Typescript Demo', function() {browser.ignoreSynchronization = true; // for non-angular websitesit('Browser Window operation', function() {// set implicit time to 30 secondsbrowser.manage().timeouts().implicitlyWait(30000);// navigate to the urlbrowser.get("https://chercher.tech/protractor/handle-browser-windows-protractor.php");// get the Session id of the Parentbrowser.getWindowHandle().then(function(parentGUID){// store the elementlet ele:WebElement = element(by.id("force-new-window"));// create object for Actions classbrowser.actions().keyDown(protractor.Key.SHIFT).click(ele).perform()});});});

Protractor Interview Questions

Recommended Readings
  • Screenshot in Protractor
  • Cookies in Protractor | Typescript | getCookie | deleteCookie | addCookie | Components
  • Database connection with Protractor
  • Mouse Actions in Protractor
  • Dynamic table | Custom Element in Protractor
  • DatePicker/Calendar Popup in Protractor

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section

Point our Mistakes and Post Your Suggestions

  • Reply
  • Kumar Ajay

    How to Launch a new Tab in Google Chrome Version 78.0.3904.108 (Official Build) (64-bit) using “protractor”: “^5.4.2”,?it('Verify the dasboard page is opening for a logged user by using url', () => { home.homepage().email_id.sendKeys('xxxxxx'); home.homepage().password.sendKeys('[emailprotected]'); home.homepage().sign_in_button.click(); browser.sleep(3000) browser.actions().keyDown(protractor.Key.CONTROL).perform().then(function () { browser.actions().sendKeys('t').perform(); }); browser.sleep(3000)});
    Reply
  • jhj

    hghjgf
    Reply
  • You might also like

    Latest Posts

    Article information

    Author: Melvina Ondricka

    Last Updated: 09/29/2022

    Views: 5355

    Rating: 4.8 / 5 (48 voted)

    Reviews: 95% of readers found this page helpful

    Author information

    Name: Melvina Ondricka

    Birthday: 2000-12-23

    Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

    Phone: +636383657021

    Job: Dynamic Government Specialist

    Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

    Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.