Java Script Executor (JSE) is an interface available in the org.openqa.selenium package. This interface has two methods executeScript & executeAsyncScript. We can execute Java script codes using these two methods.
Usually we use executeScript method. When there’s a delay in processing like webservice call, time outs then executeAsyncScript method is used. As the name indicates it is asynchronous and must signal that they are finished by invoking a call back.
1. Draw Border
Using JSE we can draw a border around a particular web element. When an exception occurs like element is not editable or something and the teststep fails, we can draw a border around that element and then take the snapshot, so while reviewing the test report, it becomes really easy to figure out which element has the issue.
driver.get(“https://login.salesforce.com\”);
WebElement ele= driver.findElement(By.xpath(“//input[@name=’username’]”));
JavascriptExecutor js = (JavascriptExecutor)driver;
String color=”red”;
js.executeScript(“arguments[0].style.border=’3px solid “+color+”‘”, ele);
2. New Tab
HTML links are defined with anchor tag <a href=“#”> and how the link should open is defined by the attribute “target”. If target is set to “_self” then upon clicking the link it will open in the same tab. If we set the value to “_blank” then it will open the link in new tab. As selenium doesn’t have the feature to open link in new tab. This approach really helps in some situations.
driver.get(“https://login.salesforce.com\”);
WebElement ele= driver.findElement(By.xpath(“//a[@id=’forgot_password_link’]”));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“arguments[0].setAttribute(‘target’,’_blank’);”, ele);
ele.click();
3. Generate Alert
Using JSE we can generate alerts in run time. Let’s say we have some issues with any field and we want to generate a custom alert then we can do so. Then we need to handle the alert by switching to alert and accept/decline etc to proceed further.
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
String message=”There is an issue with the log in button”;
js.executeScript(“alert(‘”+message+”‘);”);
js.executeScript(“confirm(‘Enter your Login credentials’);”);
js.executeScript(“prompt(‘Enter the OTP number’,’Enter OTP’);”);
4. Click Element
Sometimes we notice the locator is correct however the Selenium webdriver click method doesn’t work. Could be due to the page loading time, rendering time etc. This is one of the common scenarios faced by automation developers. So we go for Java script click method.
driver.get(“https://login.salesforce.com\”);
WebElement ele= driver.findElement(By.xpath(“//a[@id=’signup_link’]”));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“arguments[0].click();”,ele);
5. Browser Navigations
We know how to refresh a page, how to navigate forward, backward in selenium webdriver using driver.navigate().refresh/forward/back methods. We can also do the same thing in JSE. Basically we need to manipulate around history . This approach is rarely used in automation scripts.
driver.get(“https://login.salesforce.com\”);
driver.findElement(By.xpath(“//input[@name=’username’]”)).sendKeys(“abc”);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
js.executeScript(“window.history.back()”);
js.executeScript(“window.history.forward()”);
6. Open URL
Selenium has the get() method that launches the URL. In Java script executor we can use the two approaches either window.location.href or window.open(). The first approach opens the URL in the same window and the second approach opens the URL in another tab.
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“window.open(‘http://www.google.com\’);”);
js.executeScript(“window.location.href = ‘http://www.google.com\’;”);
String url=”https://login.salesforce.com\”;
String script = “window.location = \'”+url+”\'”;
js.executeScript(script);
7. Get Title
We know how to get title of a page in selenium webdriver using driver.getTitle(). We can also do the same thing in JSE. Basically we need to say return the document.title. This approach is rarely used in automation scripts.
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
String title= js.executeScript(“return document.title;”).toString();
System.out.println(title);
8. Get InnerText
We don’t have any method in selenium that gives all the text from a webpage. We do have the getPageSource method however it doesn’t give only the text. So we can use this JSE approach to get the text from a web page.
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
String title= js.executeScript(“return document.title;”).toString();
System.out.println(title);
9. Scroll Down
This is the most commonly used Java script executor method. Scrolling to the bottom of the page. We are going to say scroll the window with coordinates 0 (zero) & the height of the scroll bar. So it will go to all the way to bottom of the page.
driver.get(“http://moneyboats.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“window.scrollTo(0,document.body.scrollHeight)”);
10. Scroll Element
This is another most commonly used Java script executor method. Scroll to an element. So we don’t need to scroll to the bottom of the page, We are going to say scroll and stop it when the desired element is visible.
driver.get(“http://moneyboats.com\”);
WebElement ele = driver.findElement(By.xpath(“//h4[text()=’Awesome !’]”));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“arguments[0].scrollIntoView(true);”,ele);
11. Scroll By
We can scroll horizontally or vertically by pixels using Java script executor method window.scrollBy(x cordinate, y cordinate)
driver.get(“http://moneyboats.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
//For vertical scroll
js.executeScript(“window.scrollBy(0,600)”);
//For horizontal scroll
js.executeScript(“window.scrollBy(600,0)”);
12. Highlight Element
We can toggle the background color of an element for few seconds and that will highlight or flash the element. It helps while capturing video of the test case. Let’s say we have a webpage containing the customer details, name, dob, address, phone number etc and we need to compare the details with the data available in excel sheet. In that scenario this feature will really help as we can highlight an element for which the comparison is being done and then keep moving the highlighter to the other fields . That way we can visually see or capture the test flow. Otherwise it will just open the webpage, keep performing the comparison in the backend and after some time the test result will be displayed until then the page will be seen stuck.
driver.get(“https://login.salesforce.com\”);
WebElement ele= driver.findElement(By.xpath(“//input[@name=’username’]”));
JavascriptExecutor js = (JavascriptExecutor)driver;
String bgcolor= ele.getCssValue(“backgroundColor”);
for(int i=0;i<100;i++)
{
changecolor(“rgb(0,200,0)”,ele, driver);
changecolor(bgcolor,ele, driver);
}
public static void changecolor(String color,WebElement element, WebDriver driver)
{
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“arguments[0].style.backgroundColor='”+color+”‘”, element);
}
13. Enter Text
This is an alternative to the selenium’s sendKeys() method. We need to locate the element in the DOM by id/classname etc and then set the value attribute with the text we want to enter.
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
String value=”Biswajit”;
js.executeScript(“document.getElementById(‘username’).value='”+value+”‘;”);
14. Get Text
We can fetch the text from web elements using java script executor. This is similar to how we fetch text in selenium using getText().
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
String str= js.executeScript
(“return document.getElementById(‘forgot_password_link’).innerHTML”).toString();
System.out.println(str);
15. Domain URL
Similarly how we can get the url in selenium using getURL() method we have document.URL that returns the URL of the current webpage. We also have a method that returns the domain of the current web page. This helps while checking if the url contains some particular text or if domain contains some specific text.
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
String domain = js.executeScript(“return document.domain;”).toString();
String url=js.executeScript(“return document.URL;”).toString();
16. Get Element
Java script executor can find an element by Id and it can find elements using name, classname, tagname. For example we can get all the elements using tag name input and highlight them.
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement uname= (WebElement)js.executeScript(“return document.getElementById(\”username\”);”);
uname.sendKeys(“Biswajit”);
List<WebElement> pwd= (List<WebElement>)js.executeScript(“return document.getElementsByClassName(\”input r4 wide mb16 mt8 password\”);”);
pwd.get(0).sendKeys(“Sundara”);
List<WebElement> login= (List<WebElement>)js.executeScript(“return document.getElementsByName(\”Login\”);”);
login.get(0).click();
List<WebElement> links= (List<WebElement>)js.executeScript(“return document.getElementsByTagName(\”a\”);”);
System.out.println(links.size());
17. Check Box
Using java script executor we can select/deselect a checkbox on the page.
driver.get(“https://www.toolsqa.com/automation-practice-form\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“document.getElementById(‘profession-0’).checked=true;”);
18. Click Hidden
Using java script executor we can click on the hidden element on a web page. This is not possible in selenium. If we try to perform any action on the hidden elements using selenium then we will end up with ElementNotVisible exception.
HTML Code
<button type=”button” style=”visibility:hidden;” onclick=”myFunction()”>Click Me
</button><script>function myFunction() {alert(“hello world”);}</script>
———————————————
WebElement ele = driver.findElement(By.xpath(“//button[text()=’Click Me’]”));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“arguments[0].click();”,ele);
19. EnterText Disabled
Using java script executor we can enter text to a disabled textbox. This is not possible in selenium. If we try to perform any action on the disabled elements using selenium then we will end up with ElementNotInteractable exception.
HTML Code
Enter Name: <input type=”text” disabled></input>
———————————————————
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement ele1 = driver.findElement(By.xpath(“//input[@type=’text’]”));
js.executeScript(“arguments[0].value=’abc’;”,ele1);
20. Query Selector
Using Java script query selector we can locate the elements by CSS locators and perform the action.
driver.get(“https://login.salesforce.com\”);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“document.querySelector(\”input[type=’email’]\”).value=’abc'”);
| Get the input element in the document with class=“username” | document.querySelector(\”input.username\”).value=’abc’ |
| Get the element <input> | document.querySelector(\”input\”).value=’abc’ |
| Change the text of an element with id=“name” | document.querySelector(\”#name\”).innerHTML = \”username\”; |
| Get the first <p> element in the document where the parent is a <div> element. | document.querySelector(“\div > p\”); |
| Get the first <a> element in the document that has a “target” attribute | document.querySelector(\”a[target]\”); |
| Working on multiple elements | document.querySelector(\”h2, h3\”).style.backgroundColor = \”red\”; |
21. Date Picker
Now a days the calendar UIs are more sophisticated. If you open SpiceJet, Make my trip it doesn’t allow to enter the date using sendKeys(). If we select the calendar icon and move the cursor to next next until it reaches the desired date then it will be too much processing, we will have to run loops and the time complexity will be O(n^2 ). Instead of that we can directly inject the date into the DOM using Java script executor. One drawback of this approach is it might accept invalid date like 12/32/2019. We know there’s no date 32 in a calendar but it might accept as we are injecting the date directly into the DOM. So best practice would be to check the input date format & validity before injecting into DOM.
For example I have taken a calendar widget that has shadow DOM and we will try to inject the date into the DOM using Java script executor.
driver.get(“https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_input_date_get\”);
driver.switchTo().frame(“iframeResult”);
WebElement ele = driver.findElement(By.xpath(“//input[@id=’myDate’]”));
JavascriptExecutor js = (JavascriptExecutor)driver;
String date=”2019-02-09″;
js.executeScript(“arguments[0].setAttribute(‘value’, ‘”+date+”‘)”,ele);
Caution
Selenium imitates the real user behaviors but JSE doesn’t. For example if a field is not visible then selenium will not perform the action and throw not visible exception and the testcase will be failed. That is actually correct as the real user will also be not able to see the field to perform action. However JSE can perform the action as it interacts with the DOM not on the UI and make the test pass which is not correct. So please be cautious while using Java script executor and always prefer Selenium methods over Java script executor methods.
Hit Like/Share if you like the post and add your comment below.