Selenium WebDriver

JavaScript Executor Interface

Master JavaScript Executor interface for advanced browser operations and DOM manipulation when standard WebDriver methods are insufficient.

What is JavaScript Executor?

JavaScript Executor Interface

JavaScriptExecutor is an interface which is used to execute JavaScript through Selenium WebDriver. If we can't perform operations using selenium WebDriver methods then we use JavaScriptExecutor interface to execute actions/operations.

Interface Methods

  • 1. executeScript() method
  • 2. executeAsyncScript() method

When to Use

  • • When WebDriver methods fail
  • • For complex DOM operations
  • • Browser-specific actions
  • • Advanced interactions

JavaScript Executor Operations

16 Different Operations You Can Perform

Browser Operations

  • 1. Open URL in browser window
  • 2. Open a new tab with URL
  • 3. Navigate back
  • 4. Navigate forward
  • 5. Refresh browser

Element Operations

  • 6. Click on element
  • 7. Enter text in text box
  • 8. Handle dropdown
  • 9. Mouse over event
  • 10. Scroll down or scroll up
  • 11. Capture browser title

Advanced Operations

  • 12. Capture browser URL
  • 13. Create border for element
  • 14. Highlight element with color
  • 15. Generate custom alerts
  • 16. Closed shadow root

Basic Syntax & Setup

Converting WebDriver to JavaScript Executor

Type Casting Syntax

JavascriptExecutor js = (JavascriptExecutor) driver;

Using executeScript() Method

js.executeScript("JavaScript command here");

Browser Navigation Operations

1. Open URL in Browser Window

Syntax

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

Complete Example

package Tutorial1;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;

public class Demo1 {
    public static void main(String[] args) {
        ChromeDriver driver = new ChromeDriver();
        
        JavascriptExecutor js = (JavascriptExecutor) driver;
        
        js.executeScript("window.location='https://www.redbus.com';");
    }
}

2. Open URL in New Tab

JavaScript Approach

js.executeScript("window.open('https://www.facebook.com');");

Alternative WebDriver Approach

driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://www.facebook.com");

Complete Example

ChromeDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;

// Open URL in current window
driver.get("https://www.google.com");
Thread.sleep(4000);

// Open new URL in new TAB
js.executeScript("window.open('https://www.facebook.com');");

3. Navigate Back

JavaScript Executor Approach

js.executeScript("history.go(-4)");

Go back 4 pages using JavaScript

Alternative WebDriver Approach

driver.navigate().back();
driver.navigate().back();
driver.navigate().back();
driver.navigate().back();

Multiple back() calls for same result

4. Navigate Forward

JavaScript Executor Approach

js.executeScript("history.go(+3)");

Go forward 3 pages using JavaScript

Alternative WebDriver Approach

driver.navigate().forward();
driver.navigate().forward();
driver.navigate().forward();

Multiple forward() calls for same result

5. Refresh Browser

JavaScript Executor Approach

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

Refresh current page using JavaScript

Alternative WebDriver Approach

driver.navigate().refresh();

Standard WebDriver refresh method

Complete Navigation Example

Step-by-Step Navigation Process

ChromeDriver driver = new ChromeDriver();
driver.get("https://www.google.com");

Thread.sleep(3000);
driver.navigate().to("https://www.facebook.com");

Thread.sleep(3000);
driver.navigate().to("https://www.redbus.com");

Thread.sleep(3000);
driver.navigate().to("https://www.wikipedia.org");

Thread.sleep(3000);
driver.navigate().to("https://www.saucedemo.com");

JavascriptExecutor js = (JavascriptExecutor) driver;

Thread.sleep(3000);
// Navigate to redbus URL (go back 2 pages)
js.executeScript("history.go(-2)");

Thread.sleep(3000);
// Navigate forward to wikipedia (go forward 1 page)
js.executeScript("history.go(1);");

Thread.sleep(3000);
// Navigate back to google URL (go back 3 pages)
js.executeScript("history.go(-3);");

Thread.sleep(3000);
// Navigate forward to saucedemo URL (go forward 4 pages)
js.executeScript("history.go(+4);");

Thread.sleep(3000);
// Refresh page
js.executeScript("history.go(0);");

Element Operations

6. Click on Element

🎯 5 Ways to Click Element (IMPORTANT)

1. WebElement click() method
2. WebElement submit() method
3. Actions class click() method
4. Actions class Keys.ENTER keyword
5. JavaScriptExecutor click() method

JavaScript Executor Click Syntax

WebElement wb = driver.findElement(By.id("id value"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click()", wb);

Facebook Example - Click "Already have an account?" Link

ChromeDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/reg");
Thread.sleep(4000);

WebElement wb = driver.findElement(By.linkText("Already have an account?"));
JavascriptExecutor js = (JavascriptExecutor) driver;

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

7. Enter Text in Text Box

📝 How to Enter Text Without sendKeys() Method (IMPORTANT)

We can enter text in text box using JavaScript Executor value keyword

This is an alternative approach when sendKeys() method fails or doesn't work properly

Syntax

WebElement wb = driver.findElement(By.id("id value"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value='Expected Value';", wb);

Facebook Registration Example

ChromeDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/reg");
Thread.sleep(4000);

WebElement wb1 = driver.findElement(By.name("firstname"));
WebElement wb2 = driver.findElement(By.name("lastname"));

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].value='Sonali';", wb1);
js.executeScript("arguments[0].value='bhosale';", wb2);

8. Handle Dropdown

Dropdown Selection Syntax

WebElement wb = driver.findElement(By.id("id value"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value='Expected Value';", wb);

Date Selection Example - Select 10 Nov 2010

ChromeDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/reg");
Thread.sleep(4000);

WebElement wb1 = driver.findElement(By.name("birthday_day"));
WebElement wb2 = driver.findElement(By.name("birthday_month"));

JavascriptExecutor js = (JavascriptExecutor) driver;

// Select 10 Day
js.executeScript("arguments[0].value='10';", wb1);

// Select Nov month (11th month)
js.executeScript("arguments[0].value='11';", wb2);

// Select 2010 year using getElementsByName
js.executeScript("document.getElementsByName('birthday_year')[0].value='2010';");

Additional JavaScript Executor Operations (9-16)

🚧 Advanced Operations Coming Soon

The following operations will be covered in upcoming lessons with detailed examples:

9. Mouse over event
10. Scroll down or scroll up
11. Capture browser title
12. Capture browser URL
13. Create border for element
14. Highlight element with color
15. Generate custom alerts/confirm/prompt popups
16. Closed shadow root handling

DemoQA Dropdown Example

Dynamic Dropdown Selection on DemoQA

URL: https://demoqa.com/automation-practice-form

// Step 1: Open a chrome browser
ChromeDriver driver = new ChromeDriver();

// Step 2: Open a URL
driver.get("https://demoqa.com/automation-practice-form");

// Step 3: Locate the dropdown element
WebElement wb1 = driver.findElement(By.xpath("dropdown_xpath"));

// Step 4: Convert WebDriver object into JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;

// Step 5: Click on dropdown
js.executeScript("arguments[0].click();", wb1);

// Step 6: Locate all dropdown values
List<WebElement> listValues = driver.findElements(By.xpath("options_xpath"));

// Step 7: Iterate all values using enhanced for loop
for(WebElement value : listValues) {
    // Step 8: Capture actual dropdown value using getText() method
    String actualValue = value.getText();
    
    // Step 9: Check expected value is present or not
    if(actualValue.equals("Expected Value")) {
        // Step 10: Click on dropdown value and break the loop
        js.executeScript("arguments[0].click();", value);
        break;
    }
}

Advanced Dropdown Handling

Dynamic Dropdown Selection Process

Step-by-Step Process

  1. Locate the dropdown element
  2. Convert WebDriver object to JavaScriptExecutor
  3. Click on dropdown using JavaScript
  4. Locate all dropdown values
  5. Iterate through values using enhanced for loop
  6. Capture actual dropdown value using getText() method
  7. Check if expected value is present
  8. Click on dropdown value and break the loop

Generic Dropdown Selection Code

// Step 1: Locate dropdown element
WebElement wb1 = driver.findElement(By.xpath("dropdown_xpath"));

// Step 2: Convert to JavaScriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;

// Step 3: Click on dropdown
js.executeScript("arguments[0].click();", wb1);

// Step 4: Locate all dropdown values
List<WebElement> listValues = driver.findElements(By.xpath("options_xpath"));

// Step 5-8: Iterate and select
for(WebElement value : listValues) {
    // Step 6: Capture actual dropdown value
    String actualValue = value.getText();
    
    // Step 7: Check expected value
    if(actualValue.equals("Expected Value")) {
        // Step 8: Click and break
        js.executeScript("arguments[0].click();", value);
        break;
    }
}

📝 Assignment

🎯 Practice Assignment

Assignment URL:

https://portal2.passportindia.gov.in/AppOnlineProject/user/RegistrationBaseAction?request_locale=en

Task Instructions:

  • • Practice all JavaScript Executor operations learned in this lesson
  • • Use the Passport India registration form for hands-on practice
  • • Implement dropdown handling, text input, and element clicking
  • • Apply both JavaScript Executor and WebDriver approaches
  • • Compare the effectiveness of different methods

📝 Practice Focus Areas:

✓ Browser navigation operations
✓ Element clicking with JS Executor
✓ Text input without sendKeys()
✓ Dropdown value selection
✓ Dynamic element handling
✓ Alternative method comparison
✓ Error handling scenarios
✓ Code optimization techniques

Knowledge Check

Question 1 of 5

What is JavaScriptExecutor in Selenium?

Key Points Summary

🎯 JavaScript Executor Essentials

  • • Interface for executing JavaScript in Selenium
  • • Use when WebDriver methods fail
  • • Provides executeScript() and executeAsyncScript()
  • • Requires type casting from WebDriver

⚡ Browser Operations

  • • window.location for opening URLs
  • • window.open() for new tabs
  • • history.go() for navigation
  • • history.go(0) for refresh

📈 Element Operations

  • • arguments[0].click() for clicking
  • • arguments[0].value for text input
  • • getElementsByName for direct access
  • • Works with WebElement references

🚨 Best Practices

  • • Use as fallback when WebDriver fails
  • • Always handle exceptions properly
  • • Test across different browsers
  • • Combine with WebDriver methods effectively

SDET Mastery

Master Test Automation

Home
CurriculumPracticeQ&ACheatsheet
🍵Buy me a Chai

Automation Testing Course

Comprehensive course covering Manual Testing, Java Programming, and Selenium WebDriver

🍵Buy me a Chai
Privacy Policy•GitHub
© 2024 Automation Testing Course. All rights reserved.