Javascript Executor in Protractor

What is Javascript

A Javascript is a small chunk of program that makes a website interactive. For example, a javascript could create a pop-up alert box , or provide a dynamic dropdown menu.

JavaScript code can listen to even on the web page like reacting to a click on a button, reacting to when check a check box, or when we enter any value in to the textbar...

Javascript can change the content of the html page dynamically, it can also change the attributes of a web element like change the a button from disabled state to enabled state.

Javascript Executor :

Javascript executor allows you to run pure Javascript code irrespective of the Selenium language binding(Java, C#, Python etc.) you are using.

We should go for Javascript Executor only when we are not able to perform a particular task with our protractor like some we may not be able click an element, such cases we can go for Javascript Executor.

To use Javascript Executor, we may require little or no knowledge on java script. We can get the commands from google (I do so), so donot worry much about it, I will try to cover Javascript Executor as much as possible in this tutorial.

Javascript Executor Interface

Javascript Executor is an interface present under protractor package. We have three different javascript executor script method method in protractor :

  • executeScript()
  • executeAsyncScript()
  • executeScriptWithDescription

How to use Javascript Executor in Protractor :

As first parameters all the javascriptmethods accepts the the "javascript command as first parameter, also they accept number of paremeters as seconds (no count).


										// access the methods
										browser.executeScript("javascript command", "arguments");
										browser.executeAsyncScript("javascript command");
										browser.executeScriptWithDescription("javascript command", "description message", "arguments")
										

Now let's see how to perform all the remaining operations in using Javascript Executor interface.

Methods present in Javascript Executor

executeScript()

executeScript method executes given JavaScript in the current frame if the control is inside the frame, if the control is in page level(window level i.e outside frames) javascript will be executed in web page.

All the local variables created inside the javascript block will be destroyed once the block execution is over, but if variable is created globally, it will be present for other javascript code.

Javascript Executor just runs the javascript in the browser but it will not return any value by default, if we want to return any value from the javascript block then we must use return statement along with our javascript.

We can manipulate the returned value based on our need like asserting or to check whether contains something so on..

The code we write in javascript is either called as query or javascript command (it is not jQuery).

Example: Below code returns the title of the page.


										browser.executeScript("return document.title");
										

If Javascript code has return statement, then it could return one of the following:

  • This method returns a WebElement, if the javascript command results in HTML element.
  • A Double value is returned, if the javascript command results in Decimal value.
  • A Long value will be returned, if the javascript command results in non-decimal number value.
  • A Boolean is returned, if query results in boolean value.
  • For all other primary values String will be returned.
  • List<Object> will be returned, if query results in array. It also supports nested lists. Lists must fall under above one of the category (WebElement, Decimal value, Long, Boolean, String).
  • Map<String, Object> will be returned, if the query results in Map and values in map must fall under above category(WebElement, Decimal value, Long, Boolean, String).

Actual syntax of the executeScript method:


										executeScript(script: string | Function, ...var_args: any[]): promise.Promise;
										


Script :String 'Script' is the javascript to be executed, it must be the type of String.
var_args: any[] 'var_args' can be a number, a boolean, a String, WebElement, or a List of any combination previously mentioned types. If the given argument doesnot fall under these categories then protractor will throw an Exception.

executeAsyncScript :

I am still researching on this topic, so I will update this section very soon.

Find an Element with Javascript Executor

We can find the element with Javascript Executor, and we can perform all the operations using protractor

Steps to Find Element :
1. Open browser and navigate to url

2. Call the executeScript("Command") method from the browser object, pass "document.getElementById('lst-ib').value='cherchertech'" to find the element and to set the value


										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 websites
											it('Javascript executions', function() {
												// set implicit time to 30 seconds
												browser.manage().timeouts().implicitlyWait(30000);
												// navigate to the url
												browser.get("http://google.com");
												// find the element and set value
												browser.executeScript("document.getElementById('lst-ib').value='cherchertech'")
											});
										});
										

Output of the javascript executor program javascript-executor-protractor

Click a element with Javascript Executor

We can click an element present in the webpage using Javascript Executor

In this tutorial I have used getElementsByName which is DOM locator, this method tries to find the all the elements that has name attribute 'btnI' in the web page,

Steps to perform a click with Javascript Executor :
1. Open browser and navigate to url

2. Call the executeScript("document.getElementsByName('btnI')[0].click()") method from the browser object, this javascript command performs the click.

3. document.getElementsByName('btnI')[0].click() is the javascript command for click operation


										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 websites
											it('Javascript executions', function() {
												// set implicit time to 30 seconds
												browser.manage().timeouts().implicitlyWait(30000);
												// navigate to the url
												browser.get("http://google.com");
												// click the element
												browser.executeScript("document.getElementsByName('btnI')[0].click()")
											});
										});
										

Sendkeys with Javascript Executor

Javascript Executor has provisions for setting value to textbars / textarea basically for all the input elements, we can perform sendkeys operation using Javascript Executor in protractor

Steps to perform Sendkeys in Javascript Executor :
1. Open browser and navigate to url

2. Call the executeScript("document.getElementById('lst-ib').value='ppp'") method from the object, this javascript command sets a value to input element.

3. document.getElementById('lst-ib').value='ppp' is the javascript command for setting a value


										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 websites
											it('Javascript executions', function() {
												// set implicit time to 30 seconds
												browser.manage().timeouts().implicitlyWait(30000);
												// navigate to the url
												browser.get("http://google.com");
												// find the element and set value
												browser.executeScript("document.getElementById('lst-ib').value='chrchertech'")
											});
										});
										

Send emails in protractor

Web page Operations with Javascript Executor

We can use Javascript Executor to perform or to retrieve details about the current page in protractor.

Title of the page with Javascript Executor :

We can get the title of the webpage using Javascript Executor, using document.title command in javascript, which returns title as string

document point to the current webpage if the control is in webpage , if control is inside a frame then it point to url of the frame

		
										// return the title of the page
										browser.executeScript("return document.title");
										
										/* (same as above) get title
										browser.getTitle();*/
										


URL with Javascript Executor :

We can retrieve the URL of the current page with Javascript Executor using document.URL javascript command


										// return the url of the page
										browser.executeScript("return document.title");
										
										/* //(same as above) get url
										browser.getCurrentUrl();*/
										


Webpage loaded or not using Javascript Executor :

With Javascript Executor we can check the state of webpage loaded or not. document.readyState javascript command gives detail about page load. If page is loaded completely it return a 'Complete' as value if page is still loading it returns 'interactive' as result


										// return the state of the page load
										browser.executeScript("return document.readyState");
										

Domain Name with Javascript Executor :

We can retrieve the domain name alone from the webpage rather than full url using Javascript Executor using return document.domain javascript command
"http://chercher.tech/java/index" is the URL, "http://chercher.tech" is domain


										// return the state of the page load
										browser.executeScript("return document.domain");
										

Zoom Levels with Javascript Executor :

Javascript Executor allows user to set the zoom level while running the code, document.body.style.zoom helps to set the zoom level in the webpage.
Below code sets the zoom level to 90%.


										// set zoom level to 90%
										browser.executeScript("document.body.style.zoom='90");
										


Highlight a Element in Javascript Executor :

We can highlight the element using Javascript Executor, to highlight a element first we have to find the element uniquely. style.backgroundColor changes the background of the element to 'custom color'.


										// highlight the search bar on google.
										browser.executeScript("document.getElementById('lst-ib').style.backgroundColor='red'");
										

Browser Properties with Javascript Executor

We can retrieve browser properties using Javascript Executor

Inner - Webpage
Outer - Browser
inner-outer-height-javascript-executor

Size of Webpage in Javascript Executor :

We can get the height of the webpage using window.innerHeight command in javascript, similarly we can fetch the width of the webpage as well using window.innerWidth.

These commands will not return the total height and width of the webpage but they will return the height and width which is visible to the user.


										// height of the webpage
										browser.executeScript("window.innerHeight");
										
										// width of the webpage
										browser.executeScript("window.innerWidth");
										

Size of the browser in Javascript Executor :

Javascript Executor helps user to fetch the height and width of the browser, height of browser not only contains the webpage it also contains address bar (url bar), menubar, bookmarks bar.

We can fetch the height of the browser using window.outerHeight. Similarly we can also retrieve the width of the browser using window.outerWidth


										// height of the webpage
										browser.executeScript("window.outerHeight");
										
										// width of the webpage
										browser.executeScript("window.outerWidth");
										


Scroll By Pages in Javascript Executor :

We can scroll the webpage based on the number of pages in protractor using Javascript Executor, one page is nothing but what ever you can see on the screen for that moment. It is basically nothing but simulating 'PageDown or PgDn' key on the keyboard.

Below code scrolls the webpage by three page downs.


										// scrolls the page by three page downs
										browser.executeScript("window.scrollByPages(3)");
										


Similarly we can per page up as well in above command we have pass negative number to simulate the pageup. Below code scrolls the webpage by 5 page ups


										// scrolls the page by 5 page up
										browser.executeScript("window.scrollByPages(-5)");
										


Navigate to Url in Javascript Executor :

We normally use driver.get() and driver.navigate().to() methods present in protractor to open a webpage but we can use window.location method present in the Javascript Executor to Open a webpage.

This method navigates the user to the give URL, below code navigates user to the google page


										// Opens the Google page
										browser.executeScript("window.location="http://google.com";");
										


Maximum Scroll distance in Javascript Executor :

With Javascript Executor in Protractor we can calculate the maximum scrollable distance using window.scrollMaxY and window.scrollMaxX.

window.scrollMaxY gives detail about how much distance we can scroll Vertically, window.scrollMaxX gives maximum scroll detail about how much distance we can scroll Horizontally


										// maximum scroll distance vertically
										browser.executeScript("return window.scrollMaxY
										
										// maximum scroll distance Horizontally
										browser.executeScript("return window.scrollMaxX");										
										

When we read something we must analyze that before accepting, because everything is linked. For example try derive what else you can do with above result.

Yes, Your guess is right,

1. We can verify whether scrollbar is present or not, when Maximum scrolls are zero then there is no scroll bars.

Note for very beginners : I have used ' ! ' which changes the true to false, and false to true (most of us know it but this note is for very beginners)


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 websites
	it('Javascript executions', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		// navigate to the url
		browser.get("http://chercher.tech/protractor/javascript-executor-protractor");
		// get the maximum scroll distance Horizontally
		browser.executeScript("return window.scrollMaxX").then(function(horizontalScrollBar){
			browser.executeScript("return window.scrollMaxY").then(function(verticalScrollBar){
				if(horizontalScrollBar != "0"){
					console.log("Horizontal Scroll bar is Present");
				}else{
					console.log("Horizontal Scroll bar is Not Present");
				}
				if(verticalScrollBar != "0"){
					console.log("Vertical Scroll bar is Present");
				}else{
					console.log("Vertical Scroll bar is Not Present");
				}
			})
		});	
	});
});
				
										

Output of horizontal and vertical scroll vertical-horizontal-scrollbar-javascriptexecutor-protractor

Scroll webpage in Javascript Executor

Sometimes we may need to scroll a webpage to particular position, we cannot perform the scroll operation using protractor, During such scenarios we have to use Javascript Executor to scroll the webpage

Steps to scroll webpage in Javascript Executor :
1. Open browser and navigate to url

2. Call the executeScript("window.scrollBy(0,300)") method from the object, this javascript command scrolls the webpage to particular distance

3. window.scrollBy(0, 300) is the javascript command for scrolling a page, scrollBy(horizontalDistance,verticalDistance) accepts two parameter

1. horizontalDistance - distance to be scrolled horizontally
2. verticalDistance - distance to be scrolled vertically
We have to set 'hozontalDistance=0' for scrolling vertically, vice-versa

										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 websites
											it('Javascript executions', function() {
												// set implicit time to 30 seconds
												browser.manage().timeouts().implicitlyWait(30000);
												// navigate to the url
												browser.get("http://chercher.tech/protractor/javascript-executor-protractor");
												// scroll vertically by 300 px
												browser.executeScript("window.scrollBy(0,300)");
											});
										});
										

Scroll Into View in Javascript Executor

Sometimes we may need to scroll a webpage to particular location/element, those cases we can use scrollIntoView method in javascript to scroll


Insight :
Protractor tries to scroll to the element and then click on it. This is because protractor will not interact with an element unless it thinks that it is visible.

Scrolling to the element happens implicitly so you just need to find the item and then work with it.

Use below way only when required or when protractor fails to scroll to the element implicitly.

Steps :
1. Open browser and navigate to url

2. Find the element using DOM locator and call the scrollIntoView method.


										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 websites
											it('Javascript executions', function() {
												// set implicit time to 30 seconds
												browser.manage().timeouts().implicitlyWait(30000);
												// navigate to the url
												browser.get("http://chercher.tech/protractor/javascript-executor-protractor");
												// scroll to particular element
												browser.executeScript("document.getElementById('default').scrollIntoView(true)");
											});
										});
										

Handle Hidden division Pop Up / Calender Pop up using Protractor

Why we should not use Javascript Executor

Why is it a bad solution ?


The Protractor works similar way to an user, protractor will perform the operation only if a user(physical person) can perform the operation on element.

We can rely on protractor, if protractor says that it cannot interact with an element, then is physical person also cannot interact with the element.

So, It is better to fail the testcase when protractor methods fails instead of trying with Javascript Executor.

For example, you may have a transparent element that is covering the element that you want to click on and blocking the click action so that you can't reach it. Visually, it will be visible to you, but Protractor will correctly see it as not visible.

With above case if you try with JavaScript executor to click on that element, your test will pass, but users will not be able to access that element when they try to use your website.

Before going to try with Javascript Executor, you must try to execute your protractor code with different browser, if it works well with other browsers then only you should go for the Javascript Executor but if the test is failing in all browser then you should fail the testcase.

So user should give least priority to Javascript Executor. Sometimes slightly increasing or decreasing the protractor version or driver server version may work for you. So, donot be hasty to use Javascript Executor.

Protractor Interview Questions

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech