Friday, June 14, 2024

"Button" Handling Using JavaScriptExecutor (JSE)

 

"Button" Handling Using JavaScriptExecutor (JSE):

Sometimes, we are unable to click a button, such as 'Login', 'Sign in', or 'Save'. In such cases, we can use JavaScriptExecutor (JSE) for clicking the button.


package JavaScriptExecutorBasics;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.JavascriptExecutor;


public class BtnHandlingByJSE {


    public static void main(String[] args) {


        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lenovo\\Downloads\\chromedriver_win32 (8)\\chromedriver.exe");


        // Open Chrome browser

        WebDriver driver = new ChromeDriver();    

        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");


        // Initialize JavaScriptExecutor

        JavascriptExecutor jse = (JavascriptExecutor) driver;


        // Click 'MySubmit' button using id with JSE

        jse.executeScript("document.getElementById('MyButton').click();");


        // Get button 'type' attribute value (i.e., 'submit')

        String buttonType = (String) jse.executeScript("return document.getElementById('MyButton').type;");

        System.out.println("Button type: " + buttonType); // Output: Button type: submit


        // Get 'id' value of 'MySubmit' button using JSE

        String buttonId = (String) jse.executeScript("return document.getElementById('MyButton').id;");

        System.out.println("Button ID: " + buttonId); // Output: Button ID: MyButton


        // Get 'value' property of 'MySubmit' button (i.e., 'My Submit') using JSE

        String buttonValue = (String) jse.executeScript("return document.getElementById('MyButton').value;");

        System.out.println("Button value: " + buttonValue); // Output: Button value: My Submit


        // Homework tasks:

        // 1. Click the 'login' button using JSE

        //    JS code: document.getElementById('loginButton').click();

        //    Implement it in Java by calling executeScript() with the above JS code.

    }

}


No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...