Selenium - JavaScript Executor

Practical usage of javaScriptexecutor

Selenium Webdriver works similar way to an user does actions on the browser web pages, hence when user is not able to interact with an element on web page, even the webdriver will not be able to do so. But using javascript, we will be to interact with that webelement. 

So this doesn't provide us an accurate result, thus even a failed case may be passed due to this. To avoid this, prior to trying with JavascriptExecutor, we must try to execute our selenium code with different browser, if it behaves differently with other browsers then only we should go for the JavascriptExecutor, but if the test is failing in all browser then we should fail the testcase.

What is Javascript

A Javascript is a small chunks 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

JavascriptExecutor is a interface present under org.openqa.selenium package in Selenium Webdriver. JavascriptExecutor Interface has two abstract method which are :

1. executeScript()
2. executeAsyncScript()

executeScript(String script or Query, Object... args)

We have to cast driver object into JavascriptExecutor type to use the methods present in the JavascriptExecutor interface

JavascriptExecutor 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.

((JavascriptExecutor) driver).executeScript("return document.title");

The code we write in javascript is either called as query or javascript command.

JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;

String query = "document.getElementById('elementId').click()";

jsExecutor.executeScript(query);

or

JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;

String query ="document.querySelector(\"class='search_button']\").click()";

jsExecutor.executeScript(query);

When we should go with Javascript Executor?

We should go for Javascript Executor only when we are not able to perform a particular task with selenium. Sometimes we may not be able click a element, such cases we can go for Javascript Executor.

Basic usage of Scripts or Queries 

To get the URL of a webpage

String sText =  js.executeScript("return document.URL;").toString();
System.out.println(sText);

To get the Title of our webpage

String sText =  js.executeScript("return document.title;").toString();
System.out.println(sText);

To navigate to different page using Javascript

js.executeScript("window.location = 'https://www.softwaretestingmaterial.com");

To refresh browser window using Javascript

js.executeScript("history.go(0)");

Highlight a Element in JavascriptExecutor

This is most useful, when we need to highlight the element in the screenshot captured.

js.executeScript("document.getElementById('lst-ib').style.backgroundColor='red'");

Webpage loaded or not using JavascriptExecutor

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

js.executeScript("return document.readyState");

To click on a SubMenu which is only visible on mouse hover on Menu

js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");

To type Text in Selenium WebDriver without using sendKeys() method

js.executeScript("document.getElementById('some id').value='someValue';");

To click a Button in Selenium WebDriver using JavaScript

js.executeScript("document.getElementById('enter your element id').click();");

//or

js.executeScript("arguments[0].click();", loginButton);

To handle Checkbox

js.executeScript("document.getElementById('enter element id').checked=false;");

To get innertext of the entire webpage in Selenium

String sText =  js.executeScript("return document.documentElement.innerText;").toString();
System.out.println(sText);

To generate Alert Pop window in selenium

js.executeScript("alert('Welcome To SoftwareTestingMaterial');");

Vertical scroll - down by 500  pixels

js.executeScript("window.scrollBy(0,500)");

For scrolling till the bottom of the page we can use the code like

js.executeScript("window.scrollBy(0,document.body.scrollHeight)");

For scrolling till the bottom of the page we can use the code like

js.executeScript("window.scrollBy(0,document.body.scrollHeight)");

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

Use below way only when required or when selenium fails to scroll to the element implicitly.
Find the element using DOM locator and call the scrollIntoView method

js.executeScript("document.getElementById('default').scrollIntoView(true)");

Scroll By Pages in JavascriptExecutor : 

js.executeScript("window.scrollByPages(3)");

Maximum Scroll distance in JavascriptExecutor : 

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

js.executeScript("return window.scrollMaxY");

js.executeScript("return window.scrollMaxX");

Finding the search textbar using Javascript

object searchTextbar = js.executeScript("return document.getElementById('lst-ib')");

// we have to cast the returned object into webelement to access all the webelement related methods

((WebElement) searchTextbar).sendKeys("abc");

Finding the search textbar using selenium webDriver

driver.findElement(By.id("lst-ib")).sendKeys("abc");

Typing a keyword in the textbox

JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;

String query = "document.getElementById('searchbox').value = 'java'";

jsExecutor.executeScript(query);

To get the domain

String sText =  js.executeScript("return document.domain;").toString();
System.out.println(sText);

Zoom Levels with JavascriptExecutor

js.executeScript("document.body.style.zoom='90");

Retrieve browser properties using JavascriptExecutor

Inner - Webpage
Outer - Browser

We can get the height of the webpage using window.innerHeight command in javascript, simillarly 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.

js.executeScript("window.innerHeight");

js.executeScript("window.innerWidth");

js.executeScript("window.outerHeight");

js.executeScript("window.outerWidth");




$() - CSS

$x() - Xpath

Comments

Popular posts from this blog

QA's approach 2 Java - Understanding Static context

Selenium 4 absolute beginners - How to create Batch execution file

Technologies - Log4J - Create Log4j Configuration File - Where ? How ? What ?