Handle datePicker in selenium using JavaScript

In this article, will talk about how to Handle datePicker in selenium using JavaScript.
Suggested post to read:
In old applications, the datepicker was in old style, that is, it was a kind of dropdowns, by using select class. But in new applications now, Datepicker are not Select element.
Datepicker are in fact table with set of rows and columns. To select a date, you just have to navigate to the cell where our desired date is present. Look at the below snapshot.
So, to handle this datePicker, we will write a java script, in which firstly we will enable the datebox (which is restricted by default to enter the value manually rather than selecting it from calendar pop-up). Then We will clear that filed & then enter the date by using sendKeys() method.
Look at the below example –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HandleDatePcikerUsingJavaScript {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("https://www.redbus.in/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //This will select From date 
  WebElement elementFromDate = driver.findElement(By.id("onward_cal"));
  ((JavascriptExecutor)driver).executeScript ("document.getElementById('onward_cal').removeAttribute('readonly',0);"); // Enables the from date box
  elementFromDate.clear();
  elementFromDate.sendKeys("18-Aug-2017"); //Enter date in required format
  
  
 }

}

Hope this helps !!

How to use JavaScriptExecutor in selenium WebDriver?

In this article i will talk about how to use JavaScriptExecutor in Selenium WebDriver.

Suggested post to read:

 What is JavaScriptExecutor in selenium WebDriver?

Let us understand first what is JavaScriptExecutr. It is an interface which is used to execute JavaScript in selenium Webdriver code.

Selenium WebDriver uses pre-defined locators like id, class, Xpath, name, link etc. to locate the elements on webpage. So, in some cases, it becomes difficult to locate element or sometimes you may face consistency problem in locating element due to webpage code.

Many Situations occur in your project where code written with selenium – java (any language binding) does not work (at all or effectively).

There would be few tricky scenarios where just Webdriver object is not sufficient enough or optimum enough to handle with java for e.g. in few of my applications, the web page rendered is very long, and while doing operations with elements, I got errors. So, I used JavaScript in my script to handle the case. Some other cases where JavaScript comes handy is handling pop ups and alerts.

In another case, dropdown wasn’t working for me (it was not properly coded by using select class). It was selecting the elements with are currently visible, wasn’t searching in to the whole list. So, in this case, I need to keep scrolling down continuously & at the same time keep checking If the required option is available to select & is getting selected.

So, there are certain advantages involved when we use the two (java, JavaScript) judiciously in automation scripts. Both the languages are great in their own space.

What are the advantages of JavaScriptExecutr in Selenium?

1.      JavaScript is very efficient & accurate, as compare to the scripts written with Selenium-Java
2.     JavaScript executor allows you to run pure JavaScript code irrespective of the Selenium language binding (Java, C#, Python etc.) you are using.
3.     By using JavaScript, you can directly interact and /or alter elements on the page, more or less, like the page developer has done.
4.     JavaScript being a language which works very well with HTML offers innumerous workarounds/hacks on the page.
5.     JavaScript is recommended to use when Selenium – Java code tends to break for certain scenario, where JavaScript works perfectly.
6.     JavaScript is quite easy to pick up with the least amount of setup required. No special setup is required while using it with selenium
How to use JavaScriptExecutr (JavaScriptExecutr Syntax) –
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Where –
script – The JavaScript to execute
Arguments – The arguments to the script. (Optional)
Let us see few of the uses where we can use javaScripts in selenium WebDriver code.
       1.       To refresh browser
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
       2.       To get Webpage title
JavascriptExecutor js = (JavascriptExecutor)driver;
String sText =  js.executeScript(“return document.title;”).toString();
        3.       To click on the button
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
      where, element is the button webElement where you wanted to click.
         4.       To Scroll down the webpage
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.scrollBy(0,50)");
-> This is to scroll 50 pixels down.
If you want to scroll down till the end of webpage, then –
  js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
        5.       To navigate to webpage –
JavascriptExecutr js = (JavascriptExecutr)driver;
js.executeScript("window.location = ‘URL-TO-BE-NAVIGATED’");

          6.       To enter text in textbox using JavaScript
           JavascriptExecutr js = (JavascriptExecutr)driver; 
           js.executeScript(“document.getElementById(‘lst-ib’).value = ‘Text to be searched’;”);
Example of JavaScriptExecutor –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class JavaScriptExample {

 public static void main(String[] args) {
  
  WebDriver driver = new FirefoxDriver();

  //Navigate to google.com using javascript
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.location = 'https://www.google.co.in'");
 
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //Enter the text in textbox using javascript
  js.executeScript("document.getElementById('lst-ib').value = 'Text to be searched';");
  
  //Click on the button using javascript
  WebElement element  = driver.findElement(By.xpath("//*[@id='tsf']/div[2]/div[3]/center/input[1]"));
  js.executeScript("arguments[0].click();", element);

  //Get page Title using JavaScript
  String PageTitle =  js.executeScript("return document.title;").toString();
  System.out.println("Page title is: "+PageTitle);
  
  //To Refresh the browser using JavaScript
  js.executeScript("history.go(0)");
  
  //To Scroll Down the webpage 
    js.executeScript("window.scrollBy(0,50)");
    
    //to Scroll the webpage to bottom of page
    js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
 }

}

Hope this example helps little bit to understand how to use JavaScript in selenium – java code.