Software Testing Material

A site for software testers. We provide free online tutorials on Manual Testing, Automation Testing - Selenium, QTP, LoadRunner, Testing Tools and many more.

  • Blog
  • Tutorials
    • Manual Testing
    • Java
    • Selenium
      • TestNG
      • Maven
      • Jenkins
    • Framework
    • Katalon
    • Agile
    • SQL
    • VBScript
    • API Testing
  • Tools
    • TestLodge
    • FrogLogic GUI Tool
    • CrossBrowserTesting
    • BrowserStack
    • TestCaseLab
    • Kobiton
    • PractiTest
    • Sikuli
    • Postman
  • Interview Q & A
    • Selenium
    • TestNG
    • Test Framework
    • Explain Framework
    • Manual Testing
    • Software QA
    • Agile
    • Testing As A Career
    • General Interview Questions
    • API Testing
    • SOAP
    • JIRA
    • Protractor
  • Free Resources
  • Guest Post
    • Guest Post Guidelines
  • Training

JavaScriptExecutor in Selenium WebDriver With Examples

Last Updated on January 31, 2018 by Rajkumar

JavaScriptExecutor in Selenium WebDriver:

In general, we do click on an element using click() method in Selenium.

For example:

Java
1
driver.findElement(By.id("Id Value")).click();

Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.

It provides mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write separate script to execute JavaScript within the browser using Selenium WebDriver script. Just use predefined interface named ‘Java Script Executor’. We need to import the below package in the script.

Package:

Java
1
import org.openqa.selenium.JavascriptExecutor;

Syntax:

1
2
JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);

Script – The JavaScript to execute
Arguments –
The arguments to the script(Optional). May be empty.
Returns –
One of Boolean, Long, String, List, WebElement, or null.

Let’s see some scenarios we could handle using this Interface:

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

1
2
js.executeScript("document.getElementById('some id').value='someValue';");
js.executeScript("document.getElementById('Email').value='SoftwareTestingMaterial.com';");*/

  • To click a Button in Selenium WebDriver using JavaScript

Java
1
2
3
js.executeScript("document.getElementById('enter your element id').click();");
//or
js.executeScript("arguments[0].click();", loginButton);

  • To handle Checkbox

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

  • To generate Alert Pop window in selenium

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

  • To refresh browser window using Javascript

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

  • To get innertext of the entire webpage in Selenium

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

  • To get the Title of our webpage

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

  • To get the domain

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

  • To get the URL of a webpage

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

  • To perform Scroll on application using  Selenium

See Also: How To Scroll Web Page Down Or UP Using Selenium WebDriver

Java
1
2
3
4
//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)");

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

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

  • To navigate to different page using Javascript

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

  • To find hidden element in selenium using JavaScriptExecutor

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

Below program will guide you to handle some of the scenarios we do use in while writing scripts.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package softwareTestingMaterial;
 
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;
import org.testng.annotations.Test;
 
public class JavaScriptExecutorClassDummy {
static WebDriver driver;
@Test
public static void javaScriptExeMethod(){
System.setProperty("webdriver.gecko.driver","D://Selenium Environment//Drivers//geckodriver.exe");
driver = new FirefoxDriver();
driver.get("https://www.gmail.com");
WebElement loginButton = driver.findElement(By.xpath("//*[@id='next']"));
/*Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);
script - The JavaScript to execute
Arguments - The arguments to the script.(Optional)*/
 
                JavascriptExecutor js = (JavascriptExecutor)driver;
                //Uncomment each scenario by using Ctrl + Shift + \ (backslash) and find the solution
 
                *//to type text in Selenium WebDriver without using sendKeys() method
                js.executeScript("document.getElementById('some id').value='someValue';");
                js.executeScript("document.getElementById('Email').value='SoftwareTestingMaterial.com';");*/
 
                /*//to click a button in Selenium WebDriver using JavaScript
                //js.executeScript("arguments[0].click();", loginButton);
                //or
                js.executeScript("document.getElementById('enter your element id').click();");
                js.executeScript("document.getElementById('next').click();");*/
                /*//to handle checkbox
                js.executeScript("document.getElementById('enter element id').checked=false;");*/
/*//to generate Alert Pop window in selenium
js.executeScript("alert('hello world');");*/
/*//to refresh browser window using Javascript
js.executeScript("history.go(0)");*/
/*// to get innertext of the entire webpage in Selenium
String sText =  js.executeScript("return document.documentElement.innerText;").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 get the domain
String sText =  js.executeScript("return document.domain;").toString();
System.out.println(sText);*/
/*//to get the URL of our webpage
String sText =  js.executeScript("return document.URL;").toString();
System.out.println(sText);*/
/*//to perform Scroll on application using  Selenium
//Vertical scroll - down by 50  pixels
js.executeScript("window.scrollBy(0,50)");
// for scrolling till the bottom of the page we can use the code like
//js.executeScript("window.scrollBy(0,document.body.scrollHeight)");*/
/* // to click on a SubMenu which is only visible on mouse hover on Menu?
//Hover on Automation Menu on the MenuBar
        js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");*/
/*//to navigate to different page using Javascript?
        //Navigate to new Page
        js.executeScript("window.location = 'https://www.softwaretestingmaterial.com");*/
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

SUBSCRIBE TO GET FREE EBOOK AND REGULAR UPDATES ON SOFTWARE TESTING

Filed Under: Selenium

data-matched-content-rows-num="2" data-matched-content-columns-num="3"
Previous Article:
TestNG Exception | TestNG Tutorial
Next Article:
How To Scroll Web Page Down Or UP Using Selenium WebDriver

About the Author

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

ADVERTISEMENT

Froglogic-Squish-GUI-Tester
CrossBrowserTesting

TUTORIALS

  • Manual Testing Tutorial
  • Selenium Tutorial
  • TestNG Tutorial
  • VBScript Tutorial
  • Agile Methodology
  • SQL Tutorial for Testers
  • INTERVIEW QUESTIONS

  • Framework Interview Questions
  • Real Time Manual Testing
  • 100 Top Selenium Interview Questions
  • 30 Top TestNG Interview Questions
  • Agile Interview Questions
  • 80 SQL Interview Questions
  • TESTING TOOLS

  • Test Lodge
  • FrogLogic Squish
  • Cross Browser Testing
  • BrowserStack
  • Test Case Lab
  • Sikuli
  • © 2019 www.softwaretestingmaterial.com | About us | Privacy Policy | Contact us | Guest Post | Disclaimer | Terms of use | Sitemap