Selenium-JavascriptExecutor - Notes By ShariqSP

JavascriptExecutor

What is JavaScript Executor in Selenium?

JavaScript Executor is a feature in Selenium WebDriver that allows executing JavaScript code within the context of the current browser window or frame.

Why do we need JavaScript Executor in Selenium?

  • Handling Dynamic Elements
  • Performance Testing
  • Scrolling
  • Debugging

How to use JavaScript Executor in Selenium?

  1. Create JavaScript Executor object
  2. Execute JavaScript code
  3. Interact with Web Elements

click here to practice JavascriptExecutor

try the below

//enable disabled button
document.getElementById('hbtn').disabled = false;


//disable enabled button
document.getElementById('hbtn').disabled = true;


//send text to disabled text box
document.getElementById("dtext").value='shariq s p';


//change squarebox color
document.getElementById('sbox').style.backgroundColor ='black'


// unhide hidden button
document.getElementById('hbtn').style.visibility='visible'


// hide visible button
document.getElementById('hbtn').style.visibility='hidden'


// scroll page horizontal
window.scrollBy(1000,0)


// scroll page veritcally
window.scrollBy(0,1000)


Tasks:

            
                System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                WebDriver driver = new ChromeDriver();
                
                //scroll page in omayo blog spot vertically 100pxs
            
                driver.get("https://omayo.blogspot.com/");
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                Thread.sleep(2000);
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("window.scrollBy(0,500)");
                
                //scroll page in sixeastern blog spot horizontally 1000pxs
            
                driver.get("https://sixeastern.com/");
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                Thread.sleep(6000);
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("window.scrollBy(1000,0)");
                
                Thread.sleep(5000);
                driver.quit();

                public static void main(String[] args) throws InterruptedException {
                System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                WebDriver driver = new ChromeDriver();
                
                //	scroll page in omayo blog spot where alert will be displayed at top
                // scrollIntoView(true) for top
                // scrollIntoView(false) for bottom
            
                driver.get("https://omayo.blogspot.com/");
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                Thread.sleep(2000);
                JavascriptExecutor js = (JavascriptExecutor) driver;
                // js.executeScript("document.getElementById('alert1').scrollIntoView(true)");
                WebElement confirm = driver.findElement(By.id("confirm"));
                js.executeScript("document.getElementById('alert1').scrollIntoView(arguments[0])",true);
                   //or
                //js.executeScript("arguments[0].scrollIntoView(true)", confirm);
             
                Thread.sleep(5000);
                driver.quit();
            
                }

                //javascriptExecutor for facebook to send data to hidden field (Custom gender)
                //once you send data oyu'll not be able to see untill you click on customgender button
                            
                public static void main(String[] args) throws InterruptedException {
                    System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                    WebDriver driver = new ChromeDriver();
                    
                        //	scroll page in omayo blog spot where alert will be displayed at top
                        //  scrollIntoView(true) for top
                        //  scrollIntoView(false) for bottom
                    
                    driver.get("https://facebook.com/");
                    driver.manage().window().maximize();
                    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                    
                    JavascriptExecutor js = (JavascriptExecutor) driver;
                    Thread.sleep(2000);
                    WebElement create = driver.findElement(By.partialLinkText("Create new account"));
                    create.click();
                    Thread.sleep(2000);
                    WebElement custome_gender = driver.findElement(By.name("custom_gender"));
                    js.executeScript("arguments[0].value='male';", custome_gender);
                    
                    Thread.sleep(5000);
                    driver.quit();
                    
                    
                    
                }

               //javascriptExecutor for woodland to send data to search field  
		
                public static void main(String[] args) throws InterruptedException {
                System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                WebDriver driver = new ChromeDriver();	
                driver.get("https://www.woodlandworldwide.com/");
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                
                JavascriptExecutor js = (JavascriptExecutor) driver;
                Thread.sleep(2000);
                WebElement search = driver.findElement(By.id("standard-bare"));
                js.executeScript("document.getElementById('standard-bare').value='shariq';", search);
                
                Thread.sleep(5000);
                driver.quit();
			    }

               // javascriptExecutor for downloading jdk for windows in oracle

                public static void main(String[] args) throws InterruptedException {
                    System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                    WebDriver driver = new ChromeDriver();
                    driver.get("https://www.oracle.com/in/java/technologies/downloads/");
                    driver.manage().window().maximize();
                    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

                    JavascriptExecutor js = (JavascriptExecutor) driver;
                    Thread.sleep(2000);
                    driver.findElement(By.id("rt01tab6-java8-windows")).click();
                    Thread.sleep(2000);
                    driver.findElement(By.partialLinkText("jdk-8u401-windows-i586.exe")).click();
                    Thread.sleep(2000);
                  // js.executeScript("document.getElementById('rt01tab6-java8-windows').scrollIntoView(false)",
                    // search);
                
                    WebElement JDKdownload = driver.findElement(By.partialLinkText("Download jdk-8u401-windows-i586.exe"));
                    js.executeScript("arguments[0].click()", JDKdownload);

                    Thread.sleep(5000);
                    driver.quit();

                }

              // javascriptExecutor to send text you disabled seach in omayo webpage
              
                public static void main(String[] args) throws InterruptedException {
                    System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                    WebDriver driver = new ChromeDriver();
                    driver.get("https://omayo.blogspot.com/");
                    driver.manage().window().maximize();
                    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

                    JavascriptExecutor js = (JavascriptExecutor) driver;
                    Thread.sleep(2000);
                    WebElement disabledseacrch = driver.findElement(By.id("tb2"));
                    Thread.sleep(2000);

                    js.executeScript("document.getElementById('tb2').value='shariq';", disabledseacrch);

                    Thread.sleep(5000);
                    driver.quit();

                }

            
        

Few Other Examples of using JavaScript Executor in Selenium:

Example 1: Scrolling to an Element

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        js.executeScript("arguments[0].scrollIntoView(true);", element);

Example 2: Changing Element Style

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        js.executeScript("arguments[0].style.border='3px solid red'", element);

Example 3: Retrieving Page Title

JavascriptExecutor js = (JavascriptExecutor) driver;
        String pageTitle = (String) js.executeScript("return document.title;");
        System.out.println("Page Title: " + pageTitle);

Example 4: Clicking on a Hidden Element

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

Example 5: Returning Inner Text of an Element

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        String innerText = (String) js.executeScript("return arguments[0].innerText;", element);

Example 6: Performing a Mouse Hover

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        js.executeScript("arguments[0].dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));", element);

Example 7: Scrolling to the Bottom of the Page

JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

Example 8: Setting Attribute Value

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        js.executeScript("arguments[0].setAttribute('value', 'new value')", element);

Example 9: Focusing on an Element

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        js.executeScript("arguments[0].focus();", element);

Example 10: Checking if an Element is Visible

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        boolean isVisible = (boolean) js.executeScript("return arguments[0].offsetWidth > 0 && arguments[0].offsetHeight > 0;", element);

Example 11: Extracting URLs of All Links on a Page

JavascriptExecutor js = (JavascriptExecutor) driver;
        List links = (List) js.executeScript("return document.getElementsByTagName('a');");
        for (WebElement link : links) {
            System.out.println(link.getAttribute("href"));
        }

Example 12: Making Element Visible

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        js.executeScript("arguments[0].style.display = 'block';", element);

Example 13: Zooming In/Out of a Page

JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.body.style.zoom = '80%';");

Example 14: Disabling Right-Click Context Menu

JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.oncontextmenu = function(){return false;}");

Example 15: Checking if a Page is Fully Loaded

JavascriptExecutor js = (JavascriptExecutor) driver;
        boolean isPageLoaded = (boolean) js.executeScript("return document.readyState").equals("complete");

Example 16: Generating a Custom Alert

JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("alert('This is a custom alert!');");

Example 17: Getting Current URL

JavascriptExecutor js = (JavascriptExecutor) driver;
        String currentURL = (String) js.executeScript("return window.location.href;");

Example 18: Removing Element from DOM

JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement element = driver.findElement(By.id("elementId"));
        js.executeScript("arguments[0].parentNode.removeChild(arguments[0]);", element);

Example 19: Disabling Input Fields

JavascriptExecutor js = (JavascriptExecutor) driver;
        List inputFields = driver.findElements(By.tagName("input"));
        for (WebElement inputField : inputFields) {
            js.executeScript("arguments[0].setAttribute('disabled', 'true');", inputField);
        }

Example 20: Resizing Browser Window

JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.resizeTo(1024, 768);");

JavaScript Executor Interview Questions

  1. What is the JavaScript Executor in Selenium WebDriver?
  2. When would you use JavaScript Executor in your Selenium tests?
  3. How do you create an instance of the JavaScript Executor in Selenium WebDriver?
  4. Explain the executeScript() method in the JavaScript Executor.
  5. What are the advantages of using JavaScript Executor in Selenium WebDriver?
  6. How do you execute JavaScript commands using the JavaScript Executor?
  7. What is the difference between executeScript() and executeAsyncScript() methods?
  8. Explain some common use cases of JavaScript Executor in Selenium WebDriver.
  9. How do you return values from JavaScript code executed by the JavaScript Executor?
  10. How do you handle asynchronous JavaScript code execution using the JavaScript Executor?
  11. What exceptions can occur while using JavaScript Executor in Selenium WebDriver?
  12. Explain how you scroll to an element using JavaScript Executor.
  13. How do you highlight an element using JavaScript Executor?
  14. What is the purpose of injecting JavaScript code using the JavaScript Executor?
  15. Explain how you handle JavaScript alerts using the JavaScript Executor.
  16. How do you set attribute values of elements using JavaScript Executor?
  17. What is the role of the WebDriver's built-in JavaScript Executor in handling asynchronous JavaScript code?
  18. How do you perform JavaScript actions on hidden elements using the JavaScript Executor?
  19. Explain how you retrieve text from hidden elements using the JavaScript Executor.
  20. What are some limitations of using JavaScript Executor in Selenium WebDriver?

Multiple Choice Questions (MCQs)

  1. Which method is used to execute JavaScript code in Selenium WebDriver?
    1. executeScript()
    2. executeJavaScript()
    3. runScript()
    4. executeJS()
  2. What is the purpose of the executeAsyncScript() method in Selenium WebDriver?
    1. To execute asynchronous JavaScript code.
    2. To execute synchronous JavaScript code.
    3. To execute JavaScript alerts.
    4. To execute JavaScript code with a delay.
  3. How do you return values from JavaScript code executed by the JavaScript Executor?
    1. Using return statement
    2. Using executeAsyncScript()
    3. Using executeScript()
    4. Using waitUntil()
  4. What exceptions can occur while using JavaScript Executor in Selenium WebDriver?
    1. WebDriverException
    2. TimeoutException
    3. JavaScriptException
    4. All of the above
  5. How do you scroll to an element using JavaScript Executor?
    1. scrollToElement()
    2. scrollIntoView()
    3. scrollTo()
    4. scrollBy()
  6. What is the purpose of injecting JavaScript code using the JavaScript Executor?
    1. To interact with the web page directly using JavaScript
    2. To bypass WebDriver's limitations
    3. To improve performance of tests
    4. All of the above
  7. How do you handle JavaScript alerts using the JavaScript Executor?
    1. Using accept() and dismiss() methods
    2. Using executeScript() method
    3. Using switchTo() method
    4. Using getWindowHandles() method
  8. What is the role of the WebDriver's built-in JavaScript Executor in handling asynchronous JavaScript code?
    1. It ensures that the JavaScript code is executed asynchronously
    2. It waits for the JavaScript code to complete execution before continuing
    3. It has no role in handling asynchronous JavaScript code
    4. It executes JavaScript code with a delay
  9. What are some limitations of using JavaScript Executor in Selenium WebDriver?
    1. It may not work properly on certain browsers
    2. It may affect the performance of tests
    3. It may introduce security vulnerabilities
    4. All of the above