Javascript Executor

     


    II. Find an Element with JavascriptExecutor

    We can find the element with JavascriptExecutor, and we can perform all the operations using selenium.
    Steps to Find Element :

    1. Create an object for the Browser and navigate to the URL.
    2. Cast the driver object to JavascriptExecutor.
    3. Call the executeScript("Command") method from the object; we have to use a return statement to return a value from the browser.
    4. We have to cast the object returned from JavascriptExecutor to the web element to access all the web element-related methods.
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class FindElementJS {
    	public static void main(String[] args) {
    		// set the geckodriver.exe property
    		System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
    		// open firefox
    		WebDriver driver = new FirefoxDriver();
    		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    
    		// open webpage
    		driver.get("https://google.com");
    
    		// find the search textbar in JavascriptExecutor
    		JavascriptExecutor js = (JavascriptExecutor) driver;
    
    		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");
    
    		/* (same as above) find the search textbar in selenium
    		driver.findElement(By.id("lst-ib")).sendKeys("abc");*/
    	}
    }

    III. Click an element with JavascriptExecutor

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

    // open webpage
    driver.get("https://google.com");
    
    JavascriptExecutor js = (JavascriptExecutor) driver;
    // click i am lucky in JavascriptExecutor
    js.executeScript("document.getElementsByName('btnI')[0].click()");
    
    /* (same as above) click i am lucky button in selenium
    driver.findElement(By.name("btnI")).click();*/

    IV. Sendkeys with JavascriptExecutor

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

    // open webpage
    driver.get("https://google.com");
    
    JavascriptExecutor js = (JavascriptExecutor) driver;
    // set google search bar value
    js.executeScript("document.getElementById('lst-ib').value='chercher tech'");
    
    /* (same as above) send keys to search bar in selenium
    driver.findElement(By.id("lst-ib")).sendKeys("chercher tech");*/


    V. Scroll webpage in JavascriptExecutor

    Scrolling to the element happens implicitly in the selenium, so you just need to find the item and then work with it.
    Sometimes we may need to scroll a webpage explicitly, bring an element to view, or into a particular position; we cannot perform the scroll operation using selenium, During such scenarios, we have to use JavascriptExecutor to scroll the webpage.


    Steps to scroll webpage in JavascriptExecutor :

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

    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
    // open webpage
    driver.get("https://google.com");
    
    JavascriptExecutor js = (JavascriptExecutor) driver;
    // scroll vertically by 300 px
    js.executeScript("window.scrollBy(0, 300)");

    Scroll Into View in JavascriptExecutor
    // open webpage
    driver.get("https://chercher.tech/java/javascript-executor-selenium-webdriver");
    
    JavascriptExecutor js = (JavascriptExecutor) driver;
    // scroll to particular element
    js.executeScript("document.getElementById('default').scrollIntoView(true)");    


    VI. Web page Operations with JavascriptExecutor

    We can use JavascriptExecutor to perform or to retrieve details about the current page in selenium.

    Title of the page with JavascriptExecutor :
    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    // return the title of the page
    js.executeScript("return document.title");
    
    /* //(same as above) get title
    driver.getTitle();*/

    URL with JavascriptExecutor :

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

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

    Webpage loaded or not using JavascriptExecutor :

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

    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    // return the state of the page load
    js.executeScript("return document.readyState");

    Domain Name with JavascriptExecutor :

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

    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    // return the state of the page load
    js.executeScript("return document.domain");

    Zoom Levels with JavascriptExecutor :

    Use document.body.style.zoom helps to set the zoom level on the webpage.
    The below code sets the zoom level to 90%.

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

    Highlight an Element in JavascriptExecutor :

    We can highlight the element using JavascriptExecutor; to highlight an element first, we have to find the element uniquely. style.backgroundColor changes the background of the element to 'custom color'.

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


    VII. Browser Properties with JavascriptExecutor

    We can retrieve browser properties using JavascriptExecutor.

    1. Inner - Webpage
    2. Outer - Browser

    3. Size of Webpage in JavascriptExecutor :

      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.

      JavascriptExecutor js = (JavascriptExecutor) driver;
      
      // height of the webpage
      js.executeScript("window.innerHeight");
      
      // width of the webpage
      js.executeScript("window.innerWidth");

    4. Size of the browser in JavascriptExecutor :

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

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

      JavascriptExecutor js = (JavascriptExecutor) driver;
      
      // height of the webpage
      js.executeScript("window.outerHeight");
      
      // width of the webpage
      js.executeScript("window.outerWidth");


    Scroll By Pages in JavascriptExecutor :

    We can scroll the webpage based on the number of pages in selenium using JavascriptExecutor; one page is nothing but whatever 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.

    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    // scrolls the page by three page downs
    js.executeScript("window.scrollByPages(3)");


    Similarly, we can perform page up as well in the above command; we have passed a negative number to simulate the pageup. Below code scrolls the webpage by 5 page ups

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

    Navigate to Url in JavascriptExecutor :

    We normally use a driver.get() and driver.navigate().to() methods present in selenium webdriver to open a webpage, but we can use the window.location method present in the JavascriptExecutor to Open a webpage.

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

    JavascriptExecutor js = (JavascriptExecutor) driver;
    
    // Opens the Google page
    js.executeScript("window.location="https://google.com";");

    Maximum Scroll distance in JavascriptExecutor :

    With JavascriptExecutor in selenium, we can calculate the maximum scrollable distance using the 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

    JavascriptExecutor js = (JavascriptExecutor) driver;
    // maximum scroll distance vertically
    js.executeScript("return window.scrollMaxY
    // maximum scroll distance Horizontally
    js.executeScript("return window.scrollMaxX");

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

    Yes, Your guess is right, 1. We can verify whether the scrollbar is present or not; when Maximum scrolls are zero, then there are 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)

    public class PresenceOfScrollBar {
    	public static void main(String[] args) {
    		// set the geckodriver.exe property
    		System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
    		// open firefox
    		WebDriver driver = new FirefoxDriver();
    		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    
    		// open webpage
    		driver.get("https://chercher.tech/java/javascript-executor-selenium-webdriver");
    
    		JavascriptExecutor js = (JavascriptExecutor) driver;
    
    		// get the maximum scroll distance Horizontally
    		Object horizontalScrollBar = js.executeScript("return window.scrollMaxX");
    
    		// get the maximum scroll distance Vertically
    		Object verticalScrollBar = js.executeScript("return window.scrollMaxY");
    
    		if(! horizontalScrollBar.equals("0")){
    			System.out.println("Horizontal Scroll bar is Present");
    		}else{
    			System.out.println("Horizontal Scroll bar is Not Present");
    		}
    
    		if(! verticalScrollBar.equals("0")){
    			System.out.println("Vertical Scroll bar is Present");
    		}else{
    			System.out.println("Vertical Scroll bar is Not Present");
    		}
    	}
    }