What is jQuery and how to use it, how to run jQuery code in Selenium WebDriver are explained in this post.

What is jQuery:
  • jQuery is just a Java Script Library, it simplifies the task with less code.  jQuery reads and manipulates the DOM easily.
  • To work with jQuery, we should include jQuery library.
  • Usually we include library from CDN (content delivery network)
  • <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
Basics of jQuery:
  • jQuery select elements using CSS selector
  • jQuery provides $() or jQuery() function, it collects the group of elements with given CSS selector.
  • jQuery has a group of methods that can be applied on identified elements.
  • We can execute jQuery code in browser console by opened the website to know whether it is working or not.

Some times the actions like click will not performed, if we use simple Web Driver APIs like WebElement.click().

To overcome this we can use jQuery.

1. Run jQuery in Selenium WebDriver
  • To run jQuery we should use method executeScript() of JavaScriptExceutor interface.
  • JavascriptExecutor js=(JavascriptExecutor)driver;
    js.executeScript("...")
    
    • Here driver is the instantiation of the required browser like FirefoxDriver, ChromeDriver.
    • Provide jQuery in places of …

buy triamterene hctz online Note: 

  • If website on which we are working has by default jQuery support, we can directly execute JQuery, it won’t throw any exceptions.
  • If website has no jQuery support, we can inject jQuery and then use it, will discuss later in this post.

Here is the example to get the text of the copyright element in jquery web site refer https://jquery.com/, this site has by default jQuery support.

jQuery to get the text

JavascriptExecutor js=(JavascriptExecutor)driver;
System.out.println(js.executeScript("return $(\".copyright\").text();"));
Best Practice:

Follow the below logic to overcome the loading issues.

Before executing the jQuery code, write a logic to know jQuery as defined for the website or not and is it active or not, so that it won’t throw exception.

  • To know jQuery was defined or not, used !!window.jQuery , this returns true if it defined otherwise false.
  • To know active or not, used window.jQuery.active , this return 0 if it is active otherwise false.
  • public void isjQueryLoaded(WebDriver driver) {
        System.out.println("Waiting for ready state complete");
        (new WebDriverWait(driver, 30)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver d) {
                    JavascriptExecutor js = (JavascriptExecutor) d;
                    String readyState = js.executeScript("return document.readyState").toString();
                    System.out.println("Ready State: " + readyState);
                    return (Boolean) js.executeScript("return !!window.jQuery && window.jQuery.active == 0");
                }
            });
    }
    

Below is the complete code.

package com.exploreselenium;

import java.io.File;
import java.lang.Class;

import com.google.common.io.Resources;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.URL;

public class RunJquery {

    WebDriver driver;
    JavascriptExecutor js;

    @FindBy(id="menu-top") WebElement menu;

    @BeforeClass
    public void browserInstantiate() {
        //System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\chromedriver.exe");
        System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\geckodriver.exe");
        driver=new FirefoxDriver();
        //driver = new ChromeDriver();
        js=(JavascriptExecutor)driver;
        PageFactory.initElements(driver, this);
    }

    @Test
    public void getTextFromJquery() throws Exception{
        driver.get("https://jquery.com");
        verifyElementVisible(menu);
        isjQueryLoaded(driver);
        System.out.println("Is Jquery loaded......" + isjQueryLoaded());
        System.out.println(js.executeScript("return $(\".copyright\").text();"));

    }

    public void verifyElementVisible(WebElement element){
        new WebDriverWait(driver,30).until(ExpectedConditions.visibilityOf(element));

    }

    public void isjQueryLoaded(WebDriver driver) {
        System.out.println("Waiting for ready state complete");
        (new WebDriverWait(driver, 30)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                JavascriptExecutor js = (JavascriptExecutor) d;
                String readyState = js.executeScript("return document.readyState").toString();
                System.out.println("Ready State: " + readyState);
                return (Boolean) js.executeScript("return !!window.jQuery && window.jQuery.active == 0");
            }
        });
    }

}
Challenges faced:

Used Firefox browser #47.0.1,  below exception has been thrown

  • WebDriverException: $ is not defined

And also thrown Java script warning

  • line 7: mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial     [[Prototype]] value using Object.create

After doing lot of google search, came to know that issues with Firefox browser version #47.0.1

Solution: Issue was resolved after updated version to latest, then version changed to #50.1.0

No issues with Chrome browser.

2. How to run jQuery if website has no jQuery support/not defined by default

If we run the jQuery directly without doing any thing, it throws below exception during execution.

  • WebDriverException:$ is not defined

To overcome the issue, we can enable jQuery dynamically.

This is not a good idea, There might be a chance to get conflicts with existing JS libraries and jQuery and also even conflicts with itself if you have differing versions.

  • Keep this as a last option to get your work done.
  • And also use this logic once after you verified that jQuery was not defined by default.
    enable jQuery dynamically.
  1. First download the jquery.min.js file and then load the file and read that file as a string
    1. Downloaded file from jQuery web site https://jquery.com/download/ –> Download the compressed, production jQuery 3.1.1
    2. Placed this file in resource folder jquery.min.js path to enable jquery dynamically
    3. Used google api to load and read it as string
  2.  Use method executeScript() to enable jQuery dynamically

Below is the code.

  • URL jqueryUrl = Resources.getResource("jquery-3.1.1.min.js");
    System.out.println(jqueryUrl.getPath());
    String jqueryText = Resources.toString(jqueryUrl,Charsets.UTF_8);
    js.executeScript(jqueryText);
    

Here is the complete code to get the text from google page, as google don’t have jQuery support by default.

package com.exploreselenium;

import java.io.File;
import java.lang.Class;

import com.google.common.io.Resources;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.URL;

public class RunJquery {

    WebDriver driver;
    JavascriptExecutor js;

    @FindBy(id="lst-ib") WebElement googleTxtBox;

    @BeforeClass
    public void browserInstantiate() {
        //System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\chromedriver.exe");
        System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\geckodriver.exe");
        driver=new FirefoxDriver();
        //driver = new ChromeDriver();
        js=(JavascriptExecutor)driver;
        PageFactory.initElements(driver, this);
    }

    @Test
    public void getText() throws Exception{
        driver.get("http://google.com");
        verifyElementVisible(googleTxtBox);
        enablejQuery();
        System.out.println(js.executeScript("return $(\"div#_eEe\").text();"));
    }

    public void enablejQuery() throws Exception{
        String readyState = js.executeScript("return document.readyState").toString();
        System.out.println("Ready State: " + readyState);
        System.out.println("Is Jquery loaded......" + isjQueryLoaded());
        if(!isjQueryLoaded()) {
            URL jqueryUrl = Resources.getResource("jquery-3.1.1.min.js");
            System.out.println(jqueryUrl.getPath());
            String jqueryText = Resources.toString(jqueryUrl, Charsets.UTF_8);
            js.executeScript(jqueryText);
        }
        System.out.println("Is Jquery loaded......" + isjQueryLoaded());
    }

    public Boolean isjQueryLoaded() throws Exception {
        return (Boolean) js.executeScript("return !!window.jQuery;");
    }

}

Summary:  

In this post we learned what is jQuery, fundamentals of jQuery & how to run the jQuery in Selenium WebDriver for the both defined and not defined websites in detailed.

 

Exclude text content of child elements of the parent element in Selenium WebDriver
CSS psuedo class selector to identify an element on web page
0